I'm learning Python, and I'm trying out the with **** as ****:
statement. I figure it works much like C#'s using(****) {
, but I'm afraid I'm following outdated examples.
This is my code:
# -*- coding: iso-8859-1 -*-
import pprint
pow = 1, 2, 3
with pprint.pprint as pprint:
pprint(pow)
I assume what's happening here is pprint
in my small closure is an alias for the pprint.pprint
function. I'm getting a weird error though:
Traceback (most recent call last):
File "test.py", line 7, in <module>
with pprint.pprint as pprint:
AttributeError: __exit__
So now I'm thinking I'm using syntax from an older version of Python like I did earlier (print "Hello"
)
Why isn't my code working as expected?
The with statement is a replacement for commonly used try/finally error-handling statements. A common example of using the with statement is opening a file. To open and write to a file in Python, you can use the with statement as follows: with open("example. txt", "w") as file: file.
Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str , the type used to hold data is bytes .
with
doesn't work like that.
It's designed to automatically clean up an object at the end of a block, e.g. instead of
file = open('foo.txt')
# do stuff
close(file)
You can do
with open('foo.txt') as file:
# do stuff
and the close happens automatically.
See PEP 343 -- The "with" Statement for details and What's New in Python 2.5 - PEP 343 for some more examples of how you can use it.
The with
statement isn't intended to do what you expect. It uses the "context manager protocol", and as such, expects to be passed a context manager.
To create an alias, just assign it to a new variable:
import pprint
pow = 1, 2, 3
pp = pprint.pprint
pp(pow)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With