如何知道对象在Python中在哪里实例化?
我在一个Python模块里定义了一个类。在其他几个Python文件中,我会创建这个类的实例。这些实例在创建时会自我注册,也就是在__init__()
方法里,注册到一个单例的注册对象中。然后,我想从第三种类型的Python文件中访问这个注册对象,查看里面的对象,并且能够搞清楚这些对象是在哪些文件中创建的。
下面是一个代码示例:
Python模块文件:'/Users/myself/code/myobjectmodule.py':
@singleton
class Registry(object):
def __init__(self):
self.objects = {}
class MyObject(object):
def __init__(self, object_name):
self.object_name = object_name
Registry().objects[self.object_name] = self
根据http://www.python.org/dev/peps/pep-0318/#examples的singleton
装饰器
实例创建的Python文件:'/Users/myself/code/instance_creation_python_file.py':
from myobjectmodule import MyObject
A = MyObject('Foo')
第三个Python文件:'/Users/myself/code/registry_access.py':
from myobjectmodule import Registry
registry = Registry()
foo = registry.objects['Foo']
现在,我想要一个方法foo.get_file_of_object_creation()
。
我该如何实现这个方法呢?
补充说明:
这样做的原因是以下场景:
1. 一个框架定义了一组对象,这些对象用来指定数据源,并在加载后包含数据(MyObject)。
2. 使用这个框架的应用程序需要指定这些对象并使用它们。每个应用程序都保存在一个.py文件或一个文件夹中,文件夹的名称也指定了应用程序的名称。
3. 一个引擎为所有应用程序提供功能,但需要知道某些功能需要哪些对象来自哪个应用程序/文件。
3 个回答
这个回答有点不同,因为它没有使用 inspect.stack
,我发现这个在Python 3中特别慢。
import inspect
class Locatable:
def __new__(cls, *_args, **_kwargs):
# Background: http://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence
obj = super().__new__(cls)
obj.location = obj._initialization_location() # pylint: disable=protected-access
return obj
@staticmethod
def _initialization_location():
# Background: https://stackoverflow.com/a/42653524/
frame = inspect.currentframe()
while frame:
if frame.f_code.co_name == '<module>':
return {'module': frame.f_globals['__name__'], 'line': frame.f_lineno}
frame = frame.f_back
@property
def name(self):
module_name = self.__module__
class_name = self.__class__.__qualname__ # pylint: disable=no-member
return module_name + '.' + class_name
上面的代码是一个可以被继承的基础类。
location
属性应该包含创建这个类的模块名称,比如 mypackage.mymodule
。
虽然有很多警告说这只是调试时的好主意,但你可以使用 inspect
模块。
import inspect
def get_caller():
return inspect.stack()[2] # 1 is get_caller's caller
def trace_call():
_, filename, line, function, _, _ = get_caller()
print("Called by %r at %r:%d" % (function, filename, line))
def main():
trace_call()
main()
会产生
Called by 'main' at 'trace.py':11
不讨论为什么你想这样做,这里有一种方法可以实现:
# assume the file is saved as "temp.py"
import inspect
class RegisteredObject(object):
def __new__(cls, *args, **kwargs):
new_instance = super(RegisteredObject, cls).__new__(cls, *args, **kwargs)
stack_trace = inspect.stack()
created_at = '%s:%d' % (
stack_trace[1][1], stack_trace[1][2])
new_instance.created_at = created_at
return new_instance
def get_file_of_object_creation(self):
return self.created_at
class MyObject(RegisteredObject):
pass
def create_A():
return MyObject()
def create_B():
return MyObject()
if __name__ == '__main__':
t1 = create_A()
t2 = create_B()
t3 = create_A()
t4 = create_B()
t5 = MyObject()
print '"t1" was created at "%s"' % t1.get_file_of_object_creation()
print '"t2" was created at "%s"' % t2.get_file_of_object_creation()
print '"t3" was created at "%s"' % t3.get_file_of_object_creation()
print '"t4" was created at "%s"' % t4.get_file_of_object_creation()
print '"t5" was created at "%s"' % t5.get_file_of_object_creation()
输出结果:
$ python temp.py
"t1" was created at "temp.py:19"
"t2" was created at "temp.py:22"
"t3" was created at "temp.py:19"
"t4" was created at "temp.py:22"
"t5" was created at "temp.py:29"