Masquerade real class module

Suppose you have the following layout for a python package

./a
./a/__init__.py
./a/_b.py

inside __init__.pyyou have

from _b import *

and inside _b.py you have

class B(object): pass

If you are importing from an online invitation

>>> import a
>>> a.B
<class 'a._b.B'>
>>> 

How can I completely hide the existence of _b?

, , : , "" . , ( a), . , " ", , . , - , , , . , B _c.py, , a._b.B, . a.B, B , , .

+3
2

:

B.__module__= 'a'

, , , :

from a._b import *

(. PEP 328).

ETA :

, , , , , , __init__:

for value in globals().values():
    if inspect.isclass(value) and value.__module__.startswith('a.'):
        value.__module__= 'a'

( isinstance(value, type) inspect. __main__, __name__ 'a'.)

+5

__module__ Class B

class B(object): pass
B.__module__ = 'a'

, , .

__init__.py:

from a._b import B # change this line, when required, e.g. from a._c import B
B.__module__ = 'a'
+2

Source: https://habr.com/ru/post/1724101/


All Articles