Can global variable be passed into Python function?

Marko Rauhamaa marko at
Fri Feb 21 20:20:12 CET 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.


#!/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:
        def get(self):
            return some_list[1]
        def set(self, value):
            some_list[1] = value

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

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

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


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

if __name__ == '__main__':

More information about the Python-list mailing list