0

I am fairly new in Python. I think to rename objects like the classical

with open('filename','r') as f
   ...

is very handy and I would like to do the same with many other objects but it fails, for instance, in

dic={'a':1}                   
with dic as x
    pass

with the error: AttributeError: __enter__

I would like to know why it works in the first example but not in the second one.

Thanks!

Stefano
  • 359
  • 1
  • 5
  • 16
  • 1
    This is not merely "renaming". RTFM: https://docs.python.org/3/reference/compound_stmts.html#with – ForceBru Sep 14 '18 at 15:48
  • 2
    Any object that has an `__enter__` and `__exit__` method is a *context manager*. The purpose of `with something as x` is **not for renaming**. – juanpa.arrivillaga Sep 14 '18 at 15:48

0 Answers0