开发者

Inspect import path string from object

开发者 https://www.devze.com 2023-03-12 11:01 出处:网络
If an object is a module\'s class or function I need to retrieve the absolute impo开发者_运维知识库rt path as a string. Example:

If an object is a module's class or function I need to retrieve the absolute impo开发者_运维知识库rt path as a string. Example:

>>> from a.b.c import foo
>>> get_import_path(foo)
'a.b.c.foo'

I tried to look into inspect module but there's nothing to do that.


What your are trying to do is inherently impossible. foo simply does not know how you imported it -- it might even have been imported in multiple different ways. Example on my Linux box:

>>> from os.path import normpath
>>> from posixpath import normpath as normpath2
>>> normpath is normpath2
True

So normpath and normpath2 are the same function object. It's impossible to deduce the information in which way they were imported.

That said, it sometimes might help to look at the __module__ attribute of your function:

>>> normpath.__module__
posixpath
>>> normpath2.__module__
posixpath

The __module__ attribute is not always defined, and if it is defined, it does not always contain the information you are looking for.


Use the __file__ attribute:

>>> import string
>>> string.__file__
'/usr/lib/python2.6/string.pyc'
0

精彩评论

暂无评论...
验证码 换一张
取 消