[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can global variable be passed into Python function?

Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> But your code doesn't succeed at doing what it sets out to do. If you try 
> to call it like this:
> py> x = 23
> py> y = 42
> py> swap(x, y)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 2, in swap
> AttributeError: 'int' object has no attribute 'get'
> not only doesn't it swap the two variables, but it raises an exception. 
> Far from being a universal swap, it's merely an obfuscated function to 
> swap a few hard-coded local variables.

You are calling the function wrong. Imagine the function in C. There,
you'd have to do this:

  x = 23;
  y = 42;
  swap(&x, &y);

You've left out the ampersands and gotten a "segmentation fault."

You should have done this:

   x = 23
   y = 42

   class XP:
       def get(self):
           return x
       def set(self, value):
           nonlocal x
           x = value

   class YP:
       def get(self):
           return y
       def set(self, value):
           nonlocal y
           y = value

   swap(XP(), YP())

So we can see that Python, too, can emulate the ampersand, albeit with
some effort.