Reputation: 21507
How can I figure out how a Class or Function was imported in python? I know that __module__
exists, but that doesn't always work. An example where __module__
fails:
>>> from os.path import join
>>> join.__module__
'ntpath'
In that example, I would want to get os.path
instead. ntpath
is where the function was defined, not the package from which I imported the function.
Edit:
Specifically, the reason I'd like to get os.path
instead of ntpath
is because os.path
is platform independent whereas ntpath
only exists on Windows. Similarly, on *nix systems, os.path
is implemented using posixpath
. If nobody can give me a reliable way of solving this problem, I guess an acceptable substitute would be some kind of map I could use that maps from implementation modules back to cross platform modules. IE, to start it off it would look like this:
{
'nt' : 'os',
'ntpath' : 'os.path',
'posixpath': 'os.path',
}
I only need the modules that are part of a standard Python install (specifically 2.7).
Second Edit:
I want to make it possible to write something like this:
from pyRemote import Remote # The module I'm writing
from os.path import join
remote = Remote(hostname, username, password)
pathOnRemoteMachine = remote.join(component1, component2)
To make this work, Remote
implements __getattr__
by looking up the attribute name in the calling namespace (using some methods from inspect
.) It finds that in the calling namespace join
is a function. It needs to know where join
can be imported from, so that it can tell the remote Python instance to import that same function. Since the local Python instance could be running on a different OS from the remote Python instance (IE, local could be Windows while remote could be RedHat), I don't want the implementation specific module (ntpath
in this case) - I want the cross platform module (os.path
in this case).
I'll also handle the scenario of needing to import from a module that came from pip by telling the remote machine to download it from pip first, or the scenario of needing to import from a file written by the user by copying that file over.
So it's a huge pile of magic and hacks to provide a very elegant (IMO) way of controlling a remote Python instance using a local Python instance.
Upvotes: 1
Views: 87
Reputation: 30288
You can index into the sys.modules
, e.g.
>>> import sys
>>> from os.path import join
>>> sys.modules[join.__module__]
"<path/posixpath.pyc>"
However, this will only give you the actual module, not the name you reference, e.g. (os.path). Not sure how you can possibly tell how the function is imported, just where it is defined.
Upvotes: 2