[Tutor] Variable reference

Steven D'Aprano steve at pearwood.info
Tue Jul 7 03:58:46 CEST 2015


On Mon, Jul 06, 2015 at 07:25:10PM +0530, Suresh Nagulavancha wrote:
> Hello everyone 
> I want to know about the variables dereference

First you need to know how variables reference.

When you assign a value to a variable, we say that we "bind the value to 
the variable's name":

spam = 42

tells Python to bind 42 to the name "spam", which associates the value 
42 with the name "spam". Every program has a global scope and local 
scopes for each function. We call those "namespaces", and that is where 
Python tracks the association between names and values.

In practice, Python often uses a dict for such namespaces, but not 
always. 99.9% of the time, you don't need to care about that, just let 
Python manage the variable names.


> Code is in python 27

There is no Python 27. I think you mean "Python 2.7" (two point seven).


> Let my variable be 

> foo="hello python"
> Print foo

That is a syntax error. As a programmer, you must be precise and 
accurate about what you say. "foo" and "Foo" and "FOO" are not the same 
thing, neither is "print" and "Print" and "PRINT".


> del foo
> What del command here actually doing , is it dereferencing or deleting the variable along with value it stored?

del unbinds the value from the name and removes the name from the 
current namespace. To put it another way, it deletes *the variable* but 
not the value.

Here is another example:

    spam = "Hello world!"
    eggs = spam
    # these 2 lines can be written as 1: spam = eggs = "Hello world!"


At this point, there are two references to the string "Hello world!": 
the two names (variables), "spam" and "eggs". We can print them, pass 
them to functions, etc.

    del spam

This removes the binding from variable "spam" to the string. The string 
itself is not deleted, only the name binding ("the variable spam"). At 
this point, we can still write:

    print eggs

which is okay, because the variable eggs still exists and is still 
bound to the string. But this line:

    print spam

raises an exception, since the variable spam no longer exists. The 
string itself, "Hello world!", is not deleted until the last reference 
to it is gone.


Hope this is clear.



-- 
Steve


More information about the Tutor mailing list