在Python中获取对象的完全限定类名

时间:2021-09-06 20:25:08

For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)

出于日志记录的目的,我想检索Python对象的完全限定类名。 (完全限定,我的意思是类名,包括包和模块名。)

I know about x.__class__.__name__, but is there a simple method to get the package and module?

我知道x .__ class __.__ name__,但有一个简单的方法来获取包和模块吗?

9 个解决方案

#1


97  

With the following program

使用以下程序

#! /usr/bin/env python

import foo

def fullname(o):
  return o.__module__ + "." + o.__class__.__name__

bar = foo.Bar()
print fullname(bar)

and Bar defined as

和栏定义为

class Bar(object):
  def __init__(self, v=42):
    self.val = v

the output is

输出是

$ ./prog.py
foo.Bar

#2


21  

Consider using the inspect module which has functions like getmodule which might be what are looking for:

考虑使用具有getmodule等功能的inspect模块,它可能正在寻找:

>>>import inspect
>>>import xml.etree.ElementTree
>>>et = xml.etree.ElementTree.ElementTree()
>>>inspect.getmodule(et)
<module 'xml.etree.ElementTree' from 
        'D:\tools\python2.5.2\lib\xml\etree\ElementTree.pyc'>

#3


21  

The provided answers don't deal with nested classes. Though it's not available until Python 3.3 (PEP 3155), you really want to use __qualname__ of the class. Eventually (3.4? PEP 395), __qualname__ will also exist for modules to deal with cases where the module is renamed (i.e. when it is renamed to __main__).

提供的答案不涉及嵌套类。虽然它在Python 3.3(PEP 3155)之前不可用,但你真的想要使用该类的__qualname__。最终(3.4?PEP 395),__ equalname__也将存在于模块中,以处理重命名模块的情况(即重命名为__main__时)。

#4


10  

Here's one based on Greg Bacon's excellent answer, but with a couple of extra checks:

这是一个基于格雷格培根的优秀答案,但有几个额外的检查:

__module__ can be None (according to the docs), and also for a type like str it can be __builtin__ (which you might not want appearing in logs or whatever). The following checks for both those possibilities:

__module__可以是None(根据文档),也可以是类似str的类型,它可以是__builtin __(您可能不希望出现在日志或其他内容中)。以下检查这两种可能性:

def fullname(o):
    module = o.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return o.__class__.__name__
    return module + '.' + o.__class__.__name__

(There might be a better way to check for __builtin__. The above just relies on the fact that str is always available, and its module is always __builtin__)

(可能有更好的方法来检查__builtin__。以上只是依赖于str总是可用的事实,它的模块总是__builtin__)

#5


8  

__module__ would do the trick.

__module__可以解决这个问题。

Try:

尝试:

>>> import re
>>> print re.compile.__module__
re

This site suggests that __package__ might work for Python 3.0; However, the examples given there won't work under my Python 2.5.2 console.

该站点表明__package__可能适用于Python 3.0;但是,那里给出的示例在我的Python 2.5.2控制台下不起作用。

#6


5  

This is a hack but I'm supporting 2.6 and just need something simple:

这是一个黑客,但我支持2.6,只需要一些简单的东西:

>>> from logging.handlers import MemoryHandler as MH
>>> str(MH).split("'")[1]

'logging.handlers.MemoryHandler'

#7


2  

Since the interest of this topic is to get fully qualified names, here is a pitfall that occurs when using relative imports along with the main module existing in the same package. E.g., with the below module setup:

由于本主题的目的是获得完全限定名称,因此在使用相对导入以及同一包中存在的主模块时会出现这种缺陷。例如,使用以下模块设置:

$ cat /tmp/fqname/foo/__init__.py
$ cat /tmp/fqname/foo/bar.py
from baz import Baz
print Baz.__module__
$ cat /tmp/fqname/foo/baz.py
class Baz: pass
$ cat /tmp/fqname/main.py
import foo.bar
from foo.baz import Baz
print Baz.__module__
$ cat /tmp/fqname/foo/hum.py
import bar
import foo.bar

Here is the output showing the result of importing the same module differently:

以下是显示以不同方式导入同一模块的结果的输出:

$ export PYTHONPATH=/tmp/fqname
$ python /tmp/fqname/main.py
foo.baz
foo.baz
$ python /tmp/fqname/foo/bar.py
baz
$ python /tmp/fqname/foo/hum.py
baz
foo.baz

When hum imports bar using relative path, bar sees Baz.__module__ as just "baz", but in the second import that uses full name, bar sees the same as "foo.baz".

当hum使用相对路径导入bar时,bar将Baz .__ module__视为“baz”,但在使用全名的第二个导入中,bar看起来与“foo.baz”相同。

If you are persisting the fully-qualified names somewhere, it is better to avoid relative imports for those classes.

如果您在某处持有完全限定名称,最好避免对这些类进行相对导入。

#8


0  

None of the answers here worked for me. In my case, I was using Python 2.7 and knew that I would only be working with newstyle object classes.

这里没有任何答案对我有用。就我而言,我使用的是Python 2.7,并且知道我只会使用newstyle对象类。

def get_qualified_python_name_from_class(model):
    c = model.__class__.__mro__[0]
    name = c.__module__ + "." + c.__name__
    return name

#9


0  

Some people (e.g. https://*.com/a/16763814/5766934) arguing that __qualname__ is better than __name__. Here is an example that shows the difference:

有些人(例如https://*.com/a/16763814/5766934)认为__qualname__优于__name__。这是一个显示差异的示例:

$ cat dummy.py 
class One:
    class Two:
        pass

$ python3.6
>>> import dummy
>>> print(dummy.One)
<class 'dummy.One'>
>>> print(dummy.One.Two)
<class 'dummy.One.Two'>
>>> def full_name_with_name(klass):
...     return f'{klass.__module__}.{klass.__name__}'
>>> def full_name_with_qualname(klass):
...     return f'{klass.__module__}.{klass.__qualname__}'
>>> print(full_name_with_name(dummy.One))  # Correct
dummy.One
>>> print(full_name_with_name(dummy.One.Two))  # Wrong
dummy.Two
>>> print(full_name_with_qualname(dummy.One))  # Correct
dummy.One
>>> print(full_name_with_qualname(dummy.One.Two))  # Correct
dummy.One.Two

Note, it also works correctly for buildins:

注意,它也适用于buildins:

>>> print(full_name_with_qualname(print))
builtins.print
>>> import builtins
>>> builtins.print
<built-in function print>

#1


97  

With the following program

使用以下程序

#! /usr/bin/env python

import foo

def fullname(o):
  return o.__module__ + "." + o.__class__.__name__

bar = foo.Bar()
print fullname(bar)

and Bar defined as

和栏定义为

class Bar(object):
  def __init__(self, v=42):
    self.val = v

the output is

输出是

$ ./prog.py
foo.Bar

#2


21  

Consider using the inspect module which has functions like getmodule which might be what are looking for:

考虑使用具有getmodule等功能的inspect模块,它可能正在寻找:

>>>import inspect
>>>import xml.etree.ElementTree
>>>et = xml.etree.ElementTree.ElementTree()
>>>inspect.getmodule(et)
<module 'xml.etree.ElementTree' from 
        'D:\tools\python2.5.2\lib\xml\etree\ElementTree.pyc'>

#3


21  

The provided answers don't deal with nested classes. Though it's not available until Python 3.3 (PEP 3155), you really want to use __qualname__ of the class. Eventually (3.4? PEP 395), __qualname__ will also exist for modules to deal with cases where the module is renamed (i.e. when it is renamed to __main__).

提供的答案不涉及嵌套类。虽然它在Python 3.3(PEP 3155)之前不可用,但你真的想要使用该类的__qualname__。最终(3.4?PEP 395),__ equalname__也将存在于模块中,以处理重命名模块的情况(即重命名为__main__时)。

#4


10  

Here's one based on Greg Bacon's excellent answer, but with a couple of extra checks:

这是一个基于格雷格培根的优秀答案,但有几个额外的检查:

__module__ can be None (according to the docs), and also for a type like str it can be __builtin__ (which you might not want appearing in logs or whatever). The following checks for both those possibilities:

__module__可以是None(根据文档),也可以是类似str的类型,它可以是__builtin __(您可能不希望出现在日志或其他内容中)。以下检查这两种可能性:

def fullname(o):
    module = o.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return o.__class__.__name__
    return module + '.' + o.__class__.__name__

(There might be a better way to check for __builtin__. The above just relies on the fact that str is always available, and its module is always __builtin__)

(可能有更好的方法来检查__builtin__。以上只是依赖于str总是可用的事实,它的模块总是__builtin__)

#5


8  

__module__ would do the trick.

__module__可以解决这个问题。

Try:

尝试:

>>> import re
>>> print re.compile.__module__
re

This site suggests that __package__ might work for Python 3.0; However, the examples given there won't work under my Python 2.5.2 console.

该站点表明__package__可能适用于Python 3.0;但是,那里给出的示例在我的Python 2.5.2控制台下不起作用。

#6


5  

This is a hack but I'm supporting 2.6 and just need something simple:

这是一个黑客,但我支持2.6,只需要一些简单的东西:

>>> from logging.handlers import MemoryHandler as MH
>>> str(MH).split("'")[1]

'logging.handlers.MemoryHandler'

#7


2  

Since the interest of this topic is to get fully qualified names, here is a pitfall that occurs when using relative imports along with the main module existing in the same package. E.g., with the below module setup:

由于本主题的目的是获得完全限定名称,因此在使用相对导入以及同一包中存在的主模块时会出现这种缺陷。例如,使用以下模块设置:

$ cat /tmp/fqname/foo/__init__.py
$ cat /tmp/fqname/foo/bar.py
from baz import Baz
print Baz.__module__
$ cat /tmp/fqname/foo/baz.py
class Baz: pass
$ cat /tmp/fqname/main.py
import foo.bar
from foo.baz import Baz
print Baz.__module__
$ cat /tmp/fqname/foo/hum.py
import bar
import foo.bar

Here is the output showing the result of importing the same module differently:

以下是显示以不同方式导入同一模块的结果的输出:

$ export PYTHONPATH=/tmp/fqname
$ python /tmp/fqname/main.py
foo.baz
foo.baz
$ python /tmp/fqname/foo/bar.py
baz
$ python /tmp/fqname/foo/hum.py
baz
foo.baz

When hum imports bar using relative path, bar sees Baz.__module__ as just "baz", but in the second import that uses full name, bar sees the same as "foo.baz".

当hum使用相对路径导入bar时,bar将Baz .__ module__视为“baz”,但在使用全名的第二个导入中,bar看起来与“foo.baz”相同。

If you are persisting the fully-qualified names somewhere, it is better to avoid relative imports for those classes.

如果您在某处持有完全限定名称,最好避免对这些类进行相对导入。

#8


0  

None of the answers here worked for me. In my case, I was using Python 2.7 and knew that I would only be working with newstyle object classes.

这里没有任何答案对我有用。就我而言,我使用的是Python 2.7,并且知道我只会使用newstyle对象类。

def get_qualified_python_name_from_class(model):
    c = model.__class__.__mro__[0]
    name = c.__module__ + "." + c.__name__
    return name

#9


0  

Some people (e.g. https://*.com/a/16763814/5766934) arguing that __qualname__ is better than __name__. Here is an example that shows the difference:

有些人(例如https://*.com/a/16763814/5766934)认为__qualname__优于__name__。这是一个显示差异的示例:

$ cat dummy.py 
class One:
    class Two:
        pass

$ python3.6
>>> import dummy
>>> print(dummy.One)
<class 'dummy.One'>
>>> print(dummy.One.Two)
<class 'dummy.One.Two'>
>>> def full_name_with_name(klass):
...     return f'{klass.__module__}.{klass.__name__}'
>>> def full_name_with_qualname(klass):
...     return f'{klass.__module__}.{klass.__qualname__}'
>>> print(full_name_with_name(dummy.One))  # Correct
dummy.One
>>> print(full_name_with_name(dummy.One.Two))  # Wrong
dummy.Two
>>> print(full_name_with_qualname(dummy.One))  # Correct
dummy.One
>>> print(full_name_with_qualname(dummy.One.Two))  # Correct
dummy.One.Two

Note, it also works correctly for buildins:

注意,它也适用于buildins:

>>> print(full_name_with_qualname(print))
builtins.print
>>> import builtins
>>> builtins.print
<built-in function print>