ProgrammingBackend Developer

How does the parameter passing mechanism work in Python (call by object reference / call by sharing)? How does this reflect on mutable and immutable types, and how can unexpected changes be avoided?

Pass interviews with Hintsage AI assistant

Answer.

In Python, parameters are passed by the principle of 'call by object reference' (or 'call by sharing'). This means that the function receives a reference to the object, not the object itself. If the object is mutable, then its contents can be changed inside the function, and the changes will reflect on the external variable. For immutable objects, such as numbers or strings, changing inside the function creates a new object, leaving the original untouched.

Example for a mutable object:

def add_value(lst): lst.append(42) nums = [1, 2, 3] add_value(nums) print(nums) # [1, 2, 3, 42]

For an immutable object:

def add_value(num): num += 10 x = 5 add_value(x) print(x) # 5

Trick question.

Question: "Are variables passed by reference or by value in Python?"

Answer: Neither in the classical sense. The variable passes a reference to the object, but not the variable itself, and you cannot replace the object for the external variable.

Examples of real errors due to a lack of understanding of the nuances of the topic.


Story In one of the projects for data parsing, the function was used to filter a list. A new list was not created inside the function; filtering was done by modifying the original list. This led to the original data being erased — after several runs of the script, there were no data left.


Story A junior developer thought that strings could be changed "by reference" inside the function, as other parameters (lists) could be modified. As a result, after calling the function, the program did not receive the expected changes (the string remained unchanged), which caused incomprehensible bugs.


Story In a REST API for filtering incoming data, the developer forgot to make a copy of the parameter dictionary, and during validation, values were "lost" — parameters were removed from the original object, which broke the logic of subsequent requests.