Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Python 3.2 "with/as" do

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?

like image 860
Hubro Avatar asked Apr 24 '11 22:04

Hubro


People also ask

What does with as command in python mean?

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.

What changed in Python 3?

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 .


2 Answers

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.

like image 127
Mikel Avatar answered Nov 03 '22 00:11

Mikel


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)
like image 36
Remy Blank Avatar answered Nov 03 '22 01:11

Remy Blank