Monday, 7 December 2020

Get type object defined inside doctest by type name

I am trying to doc-test a method that accepts a module object module and a string with the name of the type type_name inside that module :

def get_type_from_string(module, type_name):
    """
    >>> class A: pass
    >>> A.__module__
    'mymodule'
    >>> get_type_from_string(sys.modules['mymodule'], 'A')
    <class '__mymodule__.A'>    <------ fails
    """
    return getattr(module, type_name)

When I am trying to get the type object with getattr (in reality, the method does more than just that), I am getting the error:

AttributeError: module 'mymodule' has no attribute 'A' 

Is it possible to doc-test this method without having to define the A class outside of the doc-test?



from Get type object defined inside doctest by type name

No comments:

Post a Comment