Obtaining the functional module of the original definition

Given a class or function, is there a way to find the full path to the module where it is originally defined? (Ie using def xxx or class xxx .)

I know there is sys.modules[func.__module__] . However, if func imported into the __init__.py package, then sys.modules will simply be redirected to this __init__.py , because the function has been moved to this namespace, as I understand it.

Specific example:

 >>> import numpy as np >>> import sys >>> np.broadcast.__module__ 'numpy' >>> sys.modules[np.broadcast.__module__] <module 'numpy' from '/Users/brad/.../site-packages/numpy/__init__.py'> 

Obviously broadcast not defined in __init__.py ; it is simply entered into the namespace with one of these from module import * statements.

It would be nice to see where np.broadcast defined in the source (regardless of the file extension, whether it be .c or .py). Is it possible?

+5
source share
1 answer

Your understanding:

However, if func imported into the __init__.py package, then sys.modules will simply be redirected to this __init__.py since the function has been introduced into this namespace as understanding goes.

wrong. __init__.py Importing an item does not affect this __module__ thing.

The behavior you see with numpy.broadcast is because the C types don't actually have a "defining module" just like the types written in Python. numpy.broadcast.__module__ == 'numpy' , because numpy.broadcast written in C and declares its name to be "numpy.broadcast" , and type C is __module__ on its behalf.

As for how to get the class or function "module of the original definition", the best thing you have is __module__ and other functions that pass through __module__ .

+2
source

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


All Articles