'python with statement with class methods: AttributeError: __enter__

I'm trying to use the with statement with a class I implemented. But I don't want the constructor of the class to be called.

I tried this:

class Model(ABC):
    def __init__(self):
        # some code that uses class variable from child classes
        # should not be called with with syntax
        pass


    @classmethod
    def __enter__(cls):
        print('call enter')
        return cls

    @classmethod
    def __exit__(cls, *args):
        print('call exit')

with Model:
  print('inside with')

but i get the error: AttributeError: __enter__

I don't understand why i get this error (my class has an enter method). Is there a way to make it work ?



Solution 1:[1]

This should work.

with Model() as m:
    print('inside with')

output:

call enter
inside with
call exit

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cyborg