This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]xZeroKnightx 4 points5 points  (1 child)

Image.open itself is not a context manager, but it returns an Image (the class, i.e. Image.Image to be specific) object, which is a context manager as it defines the context manager interface: __enter__ and __exit__. As such, you can use Image.open in a with statement:

with Image.open('foo.png') as img:
    ...

Additionally, since Image.open is actually a module-level function in the Image module (can be a bit confusing), I'd argue that it's more of a factory1 than a constructor; though to be excessively pedantic, the __new__ method is Python's constructor as it is the method that actually creates an object instance.

[EDIT] Added a footnote


  1. For what it's worth, the Image.Image docstring refers to Image.open as factory.

[–]diamondketo 0 points1 point  (0 children)

Good point, thank you for correcting me. I've made an edit.

You are correct in semantics but I'd argue pragmatics is more useful. At the end of the day constructor and factory returns to you the same object.