0

I'm using the class example from this answer to make sure certain files are always cleaned up: https://stackoverflow.com/a/865272/651779

What I would like is that when I call

pacakge_object = PackageResource()

instead of

with PackageResource() as package_obj:
    # do stuff

it gives an error explaining this class can only be used with the with statement. Is there a way of knowing if the class was initialized with with PackageResource() as package_obj: instead of pacakge_object = PackageResource()?

Community
  • 1
  • 1
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • 2
    I don't think there is, but why would you want to prevent anyone from using `package_object = PackageResource()` anyways? Just explain how to use it in the documentations. If somebody chooses to use it differently, they either know what they're doing, or it's their problem, not yours. – Markus Meskanen Aug 19 '15 at 14:51
  • The class doesn't know what it's going to be assigned to or how, unless you do something horrible and fragile with `inspect`; just document that it's best used as a context manager, and reserve the right to laugh at people who ignore you, crash and burn! – jonrsharpe Aug 19 '15 at 14:56
  • You can take a look at [this article](http://preshing.com/20110920/the-python-with-statement-by-example/), specially in the part *Implementing the Context Manager as a Class*. You may find something useful there. – Christian Tapia Aug 19 '15 at 14:56
  • @Christian that just tells you how to make a CM, which the OP has already done, not how to force the users to use the class in that way. – jonrsharpe Aug 19 '15 at 15:00
  • @jonrsharpe so, there is nothing OP can use in that link? – Christian Tapia Aug 19 '15 at 15:26
  • @Christian nothing relevant to this question – jonrsharpe Aug 19 '15 at 15:27
  • @jonrsharpe What about Mark Jansen answer. Is it possible to do something like that? – Christian Tapia Aug 19 '15 at 15:33
  • @Christian what do you mean *"is it possible"*? Yes, it is. How does that related to the article you've linked to? – jonrsharpe Aug 19 '15 at 15:35
  • It is related in the part *"...Here are the exact steps taken by the Python interpreter when it reaches the with statement:..."*. There, they mention that the `__enter__` function is called, for example. That's why I meant by, *"You may find something useful here"* in my first comment. – Christian Tapia Aug 19 '15 at 15:43

1 Answers1

0

Set a flag in your __enter__ function, and if any properties / methods of your class are called without that flag set, someone is cheating on you.

Mark Jansen
  • 1,491
  • 12
  • 24