Can global variable be passed into Python function?

Marko Rauhamaa marko at pacujo.net
Fri Feb 21 14:20:12 EST 2014


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).

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


Marko

==clip=clip=clip========================================================
#!/usr/bin/env python3

import sys

def main():
    some_list = [ 'a', 'b', 'c' ]
    some_dict = { 'few' : 'ding',
                  'good' : 'dang',
                  'men' : 'dong' }
    some_value = 'certainly'

    class SomeListElementProperty:
        """&some_list[1]"""
        def get(self):
            return some_list[1]
        def set(self, value):
            some_list[1] = value

    class SomeDictEntryProperty:
        """&some_dict["men"]"""
        def get(self):
            return some_dict['men']
        def set(self, value):
            some_dict['men'] = value

    class SomeValueProperty:
        """&some_value"""
        def get(self):
            return some_value
        def set(self, value):
            nonlocal some_value
            some_value = value

    swap(SomeListElementProperty(), SomeDictEntryProperty())
    swap(SomeListElementProperty(), SomeValueProperty())

    sys.stdout.write("{}\n".format(some_list))
    sys.stdout.write("{}\n".format(some_dict))
    sys.stdout.write("{}\n".format(some_value))

def swap(px, py):
    x = px.get()
    y = py.get()
    px.set(y)
    py.set(x)

if __name__ == '__main__':
    main()
==clip=clip=clip========================================================



More information about the Python-list mailing list