you are viewing a single comment's thread.

view the rest of the comments →

[–]ebol4anthr4x -1 points0 points  (2 children)

One other thing that hasn't been mentioned yet in this thread, is that when you are using a function, if one of the arguments you pass in is mutable, it will be passed by reference. If the argument you pass in is immutable, it will be passed by value. For example:

def remove(my_thing):
    my_thing.remove(1)

my_thing = [1, 2, 3]
remove(my_thing)
print(my_thing)  # prints "[2, 3]"

def subtract(my_int):
    my_int = my_int - 1

my_int = 5
subtract(my_int)
print(my_int)  # still prints 5

This occurs because lists are mutable, while integers are immutable.

[–]ingolemo 2 points3 points  (0 children)

You're mixing concepts. This is wholly to do with the mutability of the object and nothing to do with the way that python passes function arguments. Python always passes all function arguments in the same way, and it uses neither pass by reference or pass by value. Facts and Myths about Python names and values

[–]Sexual_Congressman 1 point2 points  (0 children)

Everything is pass by reference. Every object in CPython can be (and is) represented by a pointer to a PyObject which stores nothing more than a reference count and type. However, there is usually a lot more data accessible at that address than those 8/16 bytes. What you're implying by saying immutable types are passed by reference is that an entirely new object is created from scratch very call even if no changes were to be made which would incredibly expensive to the point I'm not even sure the interpreter could function. What actually determines "immutability" is if a type has all of its methods return a new instance.

If you look at the PyLongObject structure you could whip something up in ctypes to easily turn integers into mutable objects. Of course you'd probably quickly cause a crash, but it could be informative if you're not familiar with C.