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 :
JavaScript
x
10
10
1
def get_type_from_string(module, type_name):
2
"""
3
>>> class A: pass
4
>>> A.__module__
5
'mymodule'
6
>>> get_type_from_string(sys.modules['mymodule'], 'A')
7
<class '__mymodule__.A'> <------ fails
8
"""
9
return getattr(module, type_name)
10
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:
JavaScript
1
2
1
AttributeError: module 'mymodule' has no attribute 'A'
2
Is it possible to doc-test this method without having to define the A
class outside of the doc-test?
Advertisement
Answer
For some reason the defined A class
is not present in the __dict__
. Maybe this is a problem with the doctest itself. As a work around you can add it like this:
sys.modules[A.__module__].A = A
or
sys.modules[A.__module__].__dict__['A'] = A
JavaScript
1
12
12
1
def get_type_from_string(module, type_name):
2
"""
3
>>> import sys
4
>>> class A: pass
5
>>> A.__module__
6
'mymodule'
7
>>> sys.modules[A.__module__].A = A
8
>>> get_type_from_string(sys.modules['mymodule'], 'A')
9
<class 'mymodule.A'>
10
"""
11
return getattr(module, type_name)
12
This is how I am calling the test:
JavaScript
1
6
1
if __name__ == "__main__":
2
# import sys
3
import doctest
4
import mymodule
5
doctest.testmod(mymodule)
6