Can global variable be passed into Python function?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Feb 22 01:57:24 EST 2014


On Fri, 21 Feb 2014 21:20:12 +0200, Marko Rauhamaa wrote:

> On the question of how variables can be passed to functions, C, of
> course, has the & operator and Pascal has the "var" keyword.
> 
> An analogous thing can be achieved in Python 3 (but not in Python 2, I'm
> afraid). The & operator corresponds to an ad hoc property class as in
> the program below (not intended to be serious).

I'm glad you added that comment about not being serious. But even so, 
your code is extremely unPythonic and doesn't even succeed in doing what 
you try to accomplish:


> The program demonstrates how to write a universal "swap" function that
> interchanges two references.

For the record, there is no need for such a universal swap function in 
Python, as the right way to do it is:

x, y = y, x


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.


-- 
Steven



More information about the Python-list mailing list