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.

In, say, C++, a variable is a typed memory slot. Values live in these slots. If you want to put a value in two different variables, you have to make a copy of the value. Meanwhile, one of the types that variables can have is "reference to a variable of type Foo". Pass by value means copying the value from the argument variable into the parameter variable. Pass by reference means creating a new reference-to-variable value that refers to the argument variable, and putting that in the parameter variable.

In Python, values live somewhere on their own, and have their own types, and variables are just names for those values. There is no copying, and there are no references to variables. If you want to give a value two names, that's no problem. And when you call a function, that's all that happens—the parameter becomes another name for the same value. It's not the same as pass by value, because you're not copying values. It's not the same as pass by reference, because you're not making references to variables. There are incomplete analogies with both, but really, it's a different thing from either.

A simple example

Consider this Python code:

    def spam(eggs):
        eggs.append(1)
        eggs = [2, 3]

    ham = [0]
    spam(ham)
    print(ham)

If Python passed by value, eggs would have a copy of the value [0]. No matter what it did to that copy, the original value, in ham, would remain untouched. So, it would print out [0].

If Python passed by reference, eggs would be a reference to the variable ham. It could mutate ham's value, and even put a different value in it. So, it would print out [2, 3].

But in fact, eggs becomes a new name for the same value [0] that ham is a name for. When it mutates that value, ham sees the change. When it rebinds eggs to a different value, ham is still naming the original value. So, it prints out [0, 1].

Ways to confuse yourself

People learn early in their schooling that pass by value and pass by reference are the two options, and when they learn Python, they try to figure out which one of the two it does. If you think about assignment, but not about mutability, Python looks like pass by value. If you think about mutability, but not assignment, Python looks like pass by reference. But it's neither.

Why does Java call this "pass by value"?

In Java, there are actually two types of values—native values, like integers, and class values. With native values, when you write "int i = 1", you're creating an int-typed memory slot and copying the number 1 into it. But with class values, when you type Foo foo = new Foo()", you're creating a new Foo somewhere, and also creating a reference-to-Foo-typed memory slot and copying a reference to that new Foo into it. When you call a function that takes an int argument, Java copies the int value from your variable to the parameter. And when you call a function that takes a Foo argument, Java copies the reference-to-Foo value from your variable to the parameter. So, in that sense, Java is calling by value. (This is basically the same thing that most Python implementations actually do deep under the covers, but you don't normally have to, or want to, think about it. Java puts that right up on the surface.)

Why does Ruby call this "pass by reference"?

Basically, Ruby is emphasizing the fact that you can modify things by passing them as arguments.

This makes more sense for Ruby than for Python, because Ruby is chock full of mutating methods, and there's an in-place way to do almost everything, while Python only has in-place methods for the handful of things where it really matters. For example, in Python, there is no in-place equivalent of filter, but in Ruby, select! is the in-place equivalent of select.

But really, it's still sloppy terminology in Ruby. If you assign to a parameter inside a function (or block), it does not affect the argument any more than in Python.

So what should we call it?

People have tried to come up with good names. Before Python ever existed, Barbara Liskov realized that there was an entirely different evaluations strategy from pass by value and pass by reference, and called it "pass by object". Others have called it "pass by sharing". Or, just to confuse novices even farther, "pass by value reference". But none of these names ever gained traction; nobody is going to know what these names mean if you use them.

So, just don't call it anything. Anyone who tries to answer a question by saying, "Well, Python passes by reference [or by value, or by some obscure term no one has ever heard of], so…" is just confusing things, not explaining.

When Python's parameter evaluation strategy actually matters, you have to describe how it works and how it matters. So just do that.

When it doesn't matter, don't bring it up.

Ways to un-confuse yourself

Instead of trying to get your head around how argument passing works in Python, get your head around how variables work. That's where the big difference from languages like Java and C++ lies, and once you understand that difference, argument passing becomes simple and obvious.

How do I do real pass by reference, then?

You don't. If you want mutable objects, use mutable objects. If you want a function to re-bind a variable given to it as an argument, you're almost always making the same mistake as when you try to dynamically create variables by name.

And that should be a clue to one way you can get around it when "almost always" isn't "always": Just pass the name, as a string. (And, if it's not implicitly obvious what namespace to look the name up in, pass that information as well.)

But usually, it's both simpler and clearer to wrap your state up in some kind of mutable object—a list, a dict, an instance of some class, even a generic namespace object—and pass that around and mutate it.

What about closures?

Yes, using closures can also be a way around needing to pass by reference. This shouldn't be too surprising—closures and objects are dual concepts in a lot of ways.

I meant how do closures work, if there's no pass by reference?

Oh, you just had to ask, didn't you. :)

The simple, but inaccurate, way to think about it is that a closure stores a name as a string and a scope to look it up in. Just like I just told you not to do. But it's happening under the covers. In particular, your Python code never uses the variable name as a string. The fact that the interpreter uses the variable name as a string doesn't matter; it always uses names as strings. If you look at the attributes of a function object and its code object, you'll see the names of any globals you reference (including modules, top-level functions, etc.) any locals you create, the function parameters themselves, etc.

But if you look carefully (or think about it hard enough), you'll realize that this isn't actually sufficient for closures. Closures are implemented by storing special cell objects in the function object, which are basically references to variables in some nonlocal frame, and there are special bytecodes to load and store those variables. (The code that owns the frame uses those bytecodes to access the variables it exposes to the closure; the code inside the closure uses them to access the variables it has cells for.) You can even see one of these cell objects in Python, and read the value of the referenced variable (func.__closure__[0].cell_contents, it you're dying of curiosity), although you can't write the value this way.

And if you're now thinking, "Aha, with some bytecode hacking, I could fake call by reference". Well, yeah, but you think it'll be simpler than passing around a 1-element list so you can fake call by reference?
9

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.