Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Sun Feb 23 11:32:49 CET 2014


On Sun, Feb 23, 2014 at 8:52 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
>
>> The big difference is that in "fixed location" languages, it makes
>> sense to talk about the address of a *variable*.
>
> The address could be a symbol, too.
>
> The Python statement
>
>    xyz = 3
>
> places a number in the address "xyz".
>
> You can read the value from the address "xyz" with
>
>    locals()["xyz"]

No, you cannot. That's the exact line of thinking that leads to
problems. You are not placing a number at the address "xyz", you are
pointing the name "xyz" to the number 3. That number still exists
elsewhere.

xyz = 3
abc = xyz

Does this copy the 3 from xyz into abc? In C, it would. Those
variables might not "exist" anywhere, but they must, by definition, be
storing the integer 3. And that integer has been copied. But in
Python, no it does not. It doesn't *copy* anything. And if you fiddle
with the integer 3 in some way, making it different, it'll be
different whether you look at xyz or abc, because they're the same 3.
You can't see that with integers because Python's int is immutable,
but this is where the confusion about mutable vs immutable objects
comes from. Immutable objects behave *sufficiently similarly* to the
C/Pascal model that it's possible to think Python works the same way,
but it doesn't.

The nearest C equivalent to what I'm talking about is pointers.
(CPython objects are basically used with pointers anyway. When you get
back an object reference from a CPython API function, you get a
pointer, optionally with the responsibility for one of its
references.) This is broadly how Python objects work:

/* Python strings are immutable, so the equivalent would be a list. */
/* I'm using a string because C doesn't have a list type. */
char *xyz = strcpy(malloc(20),"Hello, world!");
char *abc = xyz;

xyz[1] = 'a';
printf("abc has: %s\n", abc);

That'll show that abc has "Hallo, world!", even though it was through
xyz that the change was made. The "thing" that is that string is the
puddle of bytes on the heap (allocated with the malloc(20) up above).
The name just has a reference to that. Creating another reference to
the same object doesn't change anything.

ChrisA



More information about the Python-list mailing list