[Tutor] is an alias a variable

Steven D'Aprano steve at pearwood.info
Sat Feb 1 01:32:48 CET 2014


On Fri, Jan 31, 2014 at 09:36:13PM +0000, Alan Gauld wrote:
> On 31/01/14 09:57, Ian D wrote:
> 
> >import longModuleName  as lmn
> >
> >or
> >
> >lmn = longModuleName
> >
> >creating an alias or assigning to a variable..... or both?
> 
> variables in Python are just names.
> There is no concept of an alias as such, its just another
> name referring to the same object.

Sounds like an alias to me :-)

Informally, an alias in programming could mean one of two things:

(1) A second name for the same object, which is what Python gives us. 
The important factor is that when you operate on the object in-place, 
say append to a list, it doesn't matter which name you use:

py> a = []  # "a" is a name for the object []
py> b = a  # an alias for the *object* named "a"
py> b.append(23)  # modify the list in place
py> a
[23]


(2) A sort of "meta-name", where the alias refers to the name itself, 
rather than it's contents. Python does *not* have this functionality, 
but it is quite similar to (for example) "pass by reference" variables 
in Pascal. If Python had this sort of alias, modifying the object 
would work the same way as it currently does:

py> a = []
py> b = a  # an "alias" for the *name* "a", not the object
py> b.append(23)
py> a
[23]

but in addition assignments to the alias would be like assignments to 
the original name. This does *not* happen in Python:

py> b = 42  # assign a new value to (alias) b
py> a
42


If you try this in Python, instead the name "b" gets the value 42, while 
the name "a" continues to refer to the list [23] as before.


-- 
Steven


More information about the Tutor mailing list