Modifying access to local variables

Michael Chermside mcherm at destiny.com
Wed Jan 9 17:41:25 CET 2002


> 
> What I wanna do is be able to write without error the following thing
> :
> 
> def foo():
>    x = z
> 
> z isn't define anywhere (not a global variable) and I want it to be of
> special class, say Myclass.
> So what I want the code to mean is the following :
> def foo():
>    z = MyClass()
>    x = z


I'm wondering if you have a little bit of confusion about what the "=" 
statement does and how variables are typed.

If you write something like this:

 >>> x = 2
 >>> x = 'a'
 >>> x = MyClass()

it should work just fine. At one moment, x is an integer, later x is a 
string, and later it's a MyClass. That's OK, because x is just a name 
("identifier"), and names don't have types. However, the objects 
themselves have types. So if you do this:

 >>> x = 2
 >>> len(x)

you'll get an exception. You'll still get the exception if you do this:

 >>> x = 2
 >>> y = x
 >>> x = 'a string'
 >>> len(y)

That's because when you wrote "y = x" it didn't make the name, "y" be 
the same as the name "x"... instead it made the name "y" refer to the 
OBJECT that "x" referred to at the moment the statement was executed. 
This is known as name binding.

So... now to get around to the point of all this. You wanted to write 
something like this:

 >>> def foo():
 >>>     x = z

where z was not a global. But that wouldn't make any sense, because when 
it tried to set the name "x" to refer to whatever "z" referred to, "z" 
wouldn't refer to ANYTHING! This is why you'd get an exception if you 
tried calling foo().

On the other hand, your real purpose was to avoid having to write 
hundreds of variable declarations. I can certainly sympathize with 
this... no one should have to write hundreds of variable declarations. 
Fortunately, Python is a big help here: you don't need to write ANY 
variable declarations.

That's right... just like in my first example (where x was an int, then 
a string, then ...), variables in Python don't have any type at all. Of 
course, the OBJECTS that they refer to have types, but the variables 
themselves don't. And what that REALLY means is that you should just not 
worry about declaring the types of your variables, and instead just 
write the code. When the variable gets assigned (bound to) a value of 
type MyClass, it will automatically be of the right type.

My apologies if I've misunderstood your question... if that's the case, 
let me know and I'll revise my answer.

-- Michael Chermside





More information about the Python-list mailing list