Python 如何通过上下文管理器强制实例化对象?
Python How to force object instantiation via Context Manager?
我想通过 class 上下文管理器强制对象实例化。所以不能直接实例化。
我实现了这个解决方案,但技术上用户仍然可以实例化对象。
class HessioFile:
"""
Represents a pyhessio file instance
"""
def __init__(self, filename=None, from_context_manager=False):
if not from_context_manager:
raise HessioError('HessioFile can be only use with context manager')
和上下文管理器:
@contextmanager
def open(filename):
"""
...
"""
hessfile = HessioFile(filename, from_context_manager=True)
有更好的解决方案吗?
我知道的None。一般如果在python里面存在,就可以想办法调用。上下文管理器本质上是一种资源管理方案...如果在管理器之外没有您的 class 用例,也许上下文管理可以集成到 [=16= 的方法中]?我建议从标准库中检查 atexit 模块。它允许您注册清理函数,其方式与上下文管理器处理清理的方式大致相同,但您可以将其捆绑到您的 class 中,这样每个实例化都有一个已注册的清理函数。可能有帮助。
值得注意的是,再多的努力也无法阻止人们使用您的代码做出愚蠢的事情。您最好的选择通常是让人们尽可能轻松地使用您的代码做一些聪明的事情。
你可以想出 hacky 的方法来 尝试 并强制执行此操作(比如检查调用堆栈以禁止直接调用你的对象,布尔属性设置在 __enter__
你在允许对实例进行其他操作之前检查),但这最终会变得一团糟,难以理解并向其他人解释。
无论如何,您还应该确定,如果需要,人们总能找到绕过它的方法。 Python 并没有真正束缚你的手,如果你想做一些愚蠢的事情,它会让你去做;负责任的成年人,对吧?
如果您需要强制执行,最好将其作为文档通知提供。这样,如果用户选择直接实例化并触发不需要的行为,那是他们没有遵循 您的代码.
准则的错误
如果您认为您的客户将遵循基本的 python 编码原则,那么您可以保证如果您不在上下文中,您的 class 中的任何方法都不会被调用。
您的客户不应该显式调用 __enter__
,因此如果调用了 __enter__
,您就知道您的客户使用了 with
语句,因此在上下文中(__exit__
将被调用)。
你只需要有一个布尔变量来帮助你记住你是在上下文中还是在上下文之外。
class Obj:
def __init__(self):
self._inside_context = False
def __enter__(self):
self._inside_context = True
print("Entering context.")
return self
def __exit__(self, *exc):
print("Exiting context.")
self._inside_context = False
def some_stuff(self, name):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
print("Doing some stuff with", name)
def some_other_stuff(self, name):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
print("Doing some other stuff with", name)
with Obj() as inst_a:
inst_a.some_stuff("A")
inst_a.some_other_stuff("A")
inst_b = Obj()
with inst_b:
inst_b.some_stuff("B")
inst_b.some_other_stuff("B")
inst_c = Obj()
try:
inst_c.some_stuff("c")
except Exception:
print("Instance C couldn't do stuff.")
try:
inst_c.some_other_stuff("c")
except Exception:
print("Instance C couldn't do some other stuff.")
这将打印:
Entering context.
Doing some stuff with A
Doing some other stuff with A
Exiting context.
Entering context.
Doing some stuff with B
Doing some other stuff with B
Exiting context.
Instance C couldn't do stuff.
Instance C couldn't do some other stuff.
由于您可能有许多方法想要“保护”不被外部上下文调用,因此您可以编写一个装饰器来避免重复相同的代码来测试您的布尔值:
def raise_if_outside_context(method):
def decorator(self, *args, **kwargs):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
return method(self, *args, **kwargs)
return decorator
然后将您的方法更改为:
@raise_if_outside_context
def some_other_stuff(self, name):
print("Doing some other stuff with", name)
我建议采用以下方法:
class MainClass:
def __init__(self, *args, **kwargs):
self._class = _MainClass(*args, **kwargs)
def __enter__(self):
print('entering...')
return self._class
def __exit__(self, exc_type, exc_val, exc_tb):
# Teardown code
print('running exit code...')
pass
# This class should not be instantiated directly!!
class _MainClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
...
def method(self):
# execute code
if self.attribute1 == "error":
raise Exception
print(self.attribute1)
print(self.attribute2)
with MainClass('attribute1', 'attribute2') as main_class:
main_class.method()
print('---')
with MainClass('error', 'attribute2') as main_class:
main_class.method()
这将输出:
entering...
attribute1
attribute2
running exit code...
---
entering...
running exit code...
Traceback (most recent call last):
File "scratch_6.py", line 34, in <module>
main_class.method()
File "scratch_6.py", line 25, in method
raise Exception
Exception
我想通过 class 上下文管理器强制对象实例化。所以不能直接实例化。
我实现了这个解决方案,但技术上用户仍然可以实例化对象。
class HessioFile:
"""
Represents a pyhessio file instance
"""
def __init__(self, filename=None, from_context_manager=False):
if not from_context_manager:
raise HessioError('HessioFile can be only use with context manager')
和上下文管理器:
@contextmanager
def open(filename):
"""
...
"""
hessfile = HessioFile(filename, from_context_manager=True)
有更好的解决方案吗?
None。一般如果在python里面存在,就可以想办法调用。上下文管理器本质上是一种资源管理方案...如果在管理器之外没有您的 class 用例,也许上下文管理可以集成到 [=16= 的方法中]?我建议从标准库中检查 atexit 模块。它允许您注册清理函数,其方式与上下文管理器处理清理的方式大致相同,但您可以将其捆绑到您的 class 中,这样每个实例化都有一个已注册的清理函数。可能有帮助。
值得注意的是,再多的努力也无法阻止人们使用您的代码做出愚蠢的事情。您最好的选择通常是让人们尽可能轻松地使用您的代码做一些聪明的事情。
你可以想出 hacky 的方法来 尝试 并强制执行此操作(比如检查调用堆栈以禁止直接调用你的对象,布尔属性设置在 __enter__
你在允许对实例进行其他操作之前检查),但这最终会变得一团糟,难以理解并向其他人解释。
无论如何,您还应该确定,如果需要,人们总能找到绕过它的方法。 Python 并没有真正束缚你的手,如果你想做一些愚蠢的事情,它会让你去做;负责任的成年人,对吧?
如果您需要强制执行,最好将其作为文档通知提供。这样,如果用户选择直接实例化并触发不需要的行为,那是他们没有遵循 您的代码.
准则的错误如果您认为您的客户将遵循基本的 python 编码原则,那么您可以保证如果您不在上下文中,您的 class 中的任何方法都不会被调用。
您的客户不应该显式调用 __enter__
,因此如果调用了 __enter__
,您就知道您的客户使用了 with
语句,因此在上下文中(__exit__
将被调用)。
你只需要有一个布尔变量来帮助你记住你是在上下文中还是在上下文之外。
class Obj:
def __init__(self):
self._inside_context = False
def __enter__(self):
self._inside_context = True
print("Entering context.")
return self
def __exit__(self, *exc):
print("Exiting context.")
self._inside_context = False
def some_stuff(self, name):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
print("Doing some stuff with", name)
def some_other_stuff(self, name):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
print("Doing some other stuff with", name)
with Obj() as inst_a:
inst_a.some_stuff("A")
inst_a.some_other_stuff("A")
inst_b = Obj()
with inst_b:
inst_b.some_stuff("B")
inst_b.some_other_stuff("B")
inst_c = Obj()
try:
inst_c.some_stuff("c")
except Exception:
print("Instance C couldn't do stuff.")
try:
inst_c.some_other_stuff("c")
except Exception:
print("Instance C couldn't do some other stuff.")
这将打印:
Entering context.
Doing some stuff with A
Doing some other stuff with A
Exiting context.
Entering context.
Doing some stuff with B
Doing some other stuff with B
Exiting context.
Instance C couldn't do stuff.
Instance C couldn't do some other stuff.
由于您可能有许多方法想要“保护”不被外部上下文调用,因此您可以编写一个装饰器来避免重复相同的代码来测试您的布尔值:
def raise_if_outside_context(method):
def decorator(self, *args, **kwargs):
if not self._inside_context:
raise Exception("This method should be called from inside context.")
return method(self, *args, **kwargs)
return decorator
然后将您的方法更改为:
@raise_if_outside_context
def some_other_stuff(self, name):
print("Doing some other stuff with", name)
我建议采用以下方法:
class MainClass:
def __init__(self, *args, **kwargs):
self._class = _MainClass(*args, **kwargs)
def __enter__(self):
print('entering...')
return self._class
def __exit__(self, exc_type, exc_val, exc_tb):
# Teardown code
print('running exit code...')
pass
# This class should not be instantiated directly!!
class _MainClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
...
def method(self):
# execute code
if self.attribute1 == "error":
raise Exception
print(self.attribute1)
print(self.attribute2)
with MainClass('attribute1', 'attribute2') as main_class:
main_class.method()
print('---')
with MainClass('error', 'attribute2') as main_class:
main_class.method()
这将输出:
entering...
attribute1
attribute2
running exit code...
---
entering...
running exit code...
Traceback (most recent call last):
File "scratch_6.py", line 34, in <module>
main_class.method()
File "scratch_6.py", line 25, in method
raise Exception
Exception