9

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 was expecting I will be getting Connection is 192.168.0.1 being printed. But, instead, Connection is 127.0.0.1 is being printed.

Unless I try to construct the connection by passing in the parameter explicitly (which is not something I wish to, as I am reluctant to make change any more on Connection with 0 parameter)

connection = Connection(globals.server_ip)

Why is this so? Is there any other techniques I can apply?

1 Answer 1

15
def __init__(self, server_ip=globals.server_ip):

The argument is bound when the method is created and not re-evaluated later. To use whatever 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 exactly the same reason a function like this would be likely to not work as intended:

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

In performance-critical code this behaviour can also be used to avoid global lookups of builtins:

def highspeed(some_builtin=some_builtin):
    # in here the lookup of some_builtin will be faster as it's in the locals
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.