파이썬에서 객체의 정규화 된 클래스 이름을 얻습니다.
로깅 목적으로 Python 객체의 정규화 된 클래스 이름을 검색하려고합니다. (정규화 된 패키지 및 모듈 이름을 포함한 클래스 이름을 의미합니다.)
에 대해 알고 x.__class__.__name__
있지만 패키지와 모듈을 얻는 간단한 방법이 있습니까?
다음 프로그램으로
#! /usr/bin/env python
import foo
def fullname(o):
# o.__module__ + "." + o.__class__.__qualname__ is an example in
# this context of H.L. Mencken's "neat, plausible, and wrong."
# Python makes no guarantees as to whether the __module__ special
# attribute is defined, so we take a more circumspect approach.
# Alas, the module name is explicitly excluded from __qualname__
# in Python 3.
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__ # Avoid reporting __builtin__
else:
return module + '.' + o.__class__.__name__
bar = foo.Bar()
print fullname(bar)
로 Bar
정의
class Bar(object):
def __init__(self, v=42):
self.val = v
출력은
$ ./prog.py
foo.Bar
제공된 답변은 중첩 클래스를 처리하지 않습니다. Python 3.3 ( PEP 3155 ) 까지는 사용할 수 없지만 실제로 __qualname__
클래스 를 사용하고 싶습니다 . 결국 (3.4? PEP 395 ) __qualname__
는 모듈의 이름이 변경되는 경우 (즉, 이름이으로 변경되는 경우)를 처리하기 위해 모듈에도 존재합니다 __main__
.
찾고있는 inspect
기능과 같은 기능을 가진 모듈을 사용하는 getmodule
것이 좋습니다.
>>>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'>
다음은 Greg Bacon의 훌륭한 답변을 기반으로하지만 몇 가지 추가 검사가 있습니다.
__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__
(을 확인하는 더 좋은 방법이있을 수 있습니다 __builtin__
. 위의 내용은 str을 항상 사용할 수 있으며 모듈은 항상 가능하다는 사실에 의존합니다 __builtin__
)
__module__
트릭을 할 것입니다.
시험:
>>> import re
>>> print re.compile.__module__
re
이 사이트 는 __package__
Python 3.0에서 작동 할 수 있다고 제안합니다 . 그러나 주어진 예제는 Python 2.5.2 콘솔에서 작동하지 않습니다.
This is a hack but I'm supporting 2.6 and just need something simple:
>>> from logging.handlers import MemoryHandler as MH
>>> str(MH).split("'")[1]
'logging.handlers.MemoryHandler'
Some people (e.g. https://stackoverflow.com/a/16763814/5766934) arguing that __qualname__
is better than __name__
. Here is an example that shows the difference:
$ 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:
>>> print(full_name_with_qualname(print))
builtins.print
>>> import builtins
>>> builtins.print
<built-in function print>
For python3.7 I use:
".".join([obj.__module__, obj.__name__])
Getting:
package.subpackage.ClassName
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".
If you are persisting the fully-qualified names somewhere, it is better to avoid relative imports for those classes.
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.
def get_qualified_python_name_from_class(model):
c = model.__class__.__mro__[0]
name = c.__module__ + "." + c.__name__
return name
참고URL : https://stackoverflow.com/questions/2020014/get-fully-qualified-class-name-of-an-object-in-python
'programing tip' 카테고리의 다른 글
R에서 "<<-"(범위 지정)을 어떻게 사용합니까? (0) | 2020.07.11 |
---|---|
Emacs를 사용하여 파일의 읽기 / 쓰기 모드를 어떻게 변경합니까? (0) | 2020.07.11 |
IFRAME이 최상위 창을 리디렉션하지 못하게하는 방법 (0) | 2020.07.11 |
파이썬의 멀티 프로세싱 풀과 키보드 인터럽트 (0) | 2020.07.11 |
숨겨둔 내용으로 패치를 포맷하는 방법 (0) | 2020.07.11 |