Skip to content
Advertisement

Python How to force object instantiation via Context Manager?

I want to force object instantiation via class context manager. So make it impossible to instantiate directly.

I implemented this solution, but technically user can still instantiate object.

JavaScript

And context manager:

JavaScript

Any better solution ?

Advertisement

Answer

If you consider that your clients will follow basic python coding principles then you can guarantee that no method from your class will be called if you are not within the context.

Your client is not supposed to call __enter__ explicitly, therefore if __enter__ has been called you know your client used a with statement and is therefore inside context (__exit__ will be called).

You just need to have a boolean variable that helps you remember if you are inside or outside context.

JavaScript

This will print:

JavaScript

Since you’ll probably have many methods that you want to “protect” from being called from outside context, then you can write a decorator to avoid repeating the same code to test for your boolean:

JavaScript

Then change your methods to:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement