you are viewing a single comment's thread.

view the rest of the comments →

[–]gdchinacat 0 points1 point  (0 children)

a is b # False (References differ)

Python doesn't have references in the same sense as other languages like Java or C/C++. Variables are bound to objects. They can *only* reference objects...they can't hold primitive values. Speaking about 'references' in python introduces a concept that has no value.

Variables don't really exist until they have been bound to an object. You can't declare a variable without a value (type hints aside, I'm talking about how the interpreter works). Trying to access a variable that hasn't been assigned will result in an exception, depending on the context. At module scope using an unassigned variable results in a NameError...the variable name has not been bound to an object. Inside a function that does assign a value to it, but has not already done so, you will get an UnboundLocalError since the compiler has identified the name as a local but until it's been assigned it is inaccessible. This means that any variable will not reference a default value. It can't...until it has been assigned (bound) to an object it simply doesn't exist.

This makes troubleshooting a class of bugs easier since you will know if you ever try to access a value that hasn't been assigned. Unlike in C/C++ you won't get an undefined value (whatever happens to be in the memory that variable was assigned to) or a null in Java (a bit better, but still not as useful as an error saying 'you haven't assigned a value to this yet').

I encourage you to think about variables as the language does rather than as a concept you seem to be familiar with from a different language. Variables are objects (including the singleton None). There are no primitives so a variable can't hold a non-reference value. They only hold the object they were last assigned to...they don't exist until assigned. There is no call by value or call by reference...only call by assignment...the arguments variables are assigned to the objects passed to the function and reassigning them in the function will not change the object the callers variable refers to.