Using a global variable as a default parameter

a.py

#!c:/Python27/python.exe -u

from connection import Connection
import globals

globals.server_ip = '192.168.0.1'
connection = Connection()

globals.py

#!c:/Python27/python.exe -u

server_ip = '127.0.0.1'

connection.py

import globals

class Connection:        
    def __init__(self, server_ip = globals.server_ip):
        print 'Connection is ' + server_ip + '\n'

I expected to print Connection is 192.168.0.1. But instead it is printed Connection is 127.0.0.1.

If I don’t try to build a connection by explicitly passing it (which I don’t want, since I don’t want to change the connection with parameter 0 anymore)

connection = Connection(globals.server_ip)

Why is this so? Are there any other methods that I can apply?

+5
source share
1 answer
def __init__(self, server_ip=globals.server_ip):

The argument is bound when the method is created and is not redefined later. To use what is the current value, use something like this:

def __init__(self, server_ip=None):
    if server_ip is None:
        server_ip = globals.server_ip

Btw, for the same reason, such a function will most likely not work as intended:

def foobar(foo=[]):
    foo.append('bar')
    return foo

:

def highspeed(some_builtin=some_builtin):
    # in here the lookup of some_builtin will be faster as it in the locals
+10

All Articles