Python如何通过Context Manager强制对象实例化?

问题描述 投票:4回答:4

我想通过类上下文管理器强制对象实例化。所以不可能直接实例化。

我实现了这个解决方案,但从技术上讲,用户仍然可以实例化对象。

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)

更好的解决方案?

python contextmanager
4个回答
2
投票

没有我知道的。通常,如果它存在于python中,您可以找到一种方法来调用它。一个上下文管理器本质上是一个资源管理方案......如果你的类在管理器之外没有用例,也许上下文管理可以集成到类的方法中?我建议从标准库中查看atexit模块。它允许您以与上下文管理器处理清理相同的方式注册清理函数,但您可以将其捆绑到您的类中,以便每个实例都具有已注册的清理函数。可能有帮助。

值得注意的是,没有多少努力会阻止人们使用您的代码做出愚蠢的事情。您最好的选择通常是让人们尽可能轻松地使用您的代码进行智能操作。


3
投票

如果您认为您的客户端将遵循基本的python编码原则,那么您可以保证如果您不在上下文中,则不会调用您的类中的任何方法。

您的客户不应该明确地调用__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)

0
投票

您可以考虑使用hacky方法来尝试并强制执行此操作(例如检查调用堆栈以禁止直接调用您的对象,在您允许对实例执行其他操作之前检查的__enter__上设置的布尔属性)但最终会变得混乱了解并向他人解释。

无论如何,你还应该确定,如果需要,人们总能找到绕过它的方法。如果你想做一些愚蠢的事情,它可以让你做到这一点;负责任的大人吧?

如果您需要执行,最好将其作为文档通知提供。这样,如果用户选择直接实例化并触发不需要的行为,那么不遵循代码指南就是他们的错。


0
投票

我建议采用以下方法:

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
© www.soinside.com 2019 - 2024. All rights reserved.