Does Python pass by value, or pass by reference?

Neither.

If you twist around how you interpret the terms, you can call it either. Java calls the same evaluation strategy "pass by value", while Ruby calls it "pass by reference". But the Python documentation carefully avoids using either term, which is smart.

(I've been told that Jeff Knupp has a similar blog post called Is Python call-by-value or call-by-reference? Neither. His seems like it might be more accessible than mine, and it covers most of the same information, so maybe go read that if you get confused here, or maybe even read his first and then just skim mine.)

Variables and values

The distinction between "pass by value" and "pass by reference" is all about variables. Which is why it doesn't apply to Python.
9

In database apps, you often want to create tables, views, and indices only if they don't already exist, so they do the setup work the first time, but don't blow away all of your data every subsequent time. So SQL has a special "IF NOT EXISTS" clause you can add to the various CREATE statements.

Occasionally, you want to do the same thing in Python. For example, this StackOverflow user likes to re-run the same script over and over in the interactive session (e.g., by hitting F5 in the IDE).

Sometimes you want to write a round-trippable __repr__ method--that is, you want the string representation to be valid Python code that generates an equivalent object to the one you started with.

First, ask yourself whether you really want this. A round-trippable repr is very nice for playing with your objects in an interactive session--but if you're trying to use repr as a serialization format, don't do that.

Many novices notice that, for many types, repr and eval are perfect opposites, and assume that this is a great way to serialize their data:

def save(path, *things): with open(path, 'w') as f: for thing in things: f.write(repr(thing) + '\n') def load(path): with open(path) as f: return [eval(line) for line in f]

If you get lucky, you start running into problems, because some objects don't have a round-trippable repr. If you don't get lucky, you run into the _real_ problems later on.
1
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.