Unexpected python behaviour

R

Richard Philips

Consider the script:

def test(drivers={}):
if drivers:
print drivers
else:
drivers["A"] = "B"

if __name__ == "__main__":
test()
test()

prints in stdout:
{'A': 'B'}

I expected that nothing would be displayed.
I do not understand this behaviour (python2.3 on WinXP and Linux).

If anybody can explain this situation, you are welcome.

Thank you.


--
================================================================
Dr. Richard PHILIPS
University of Antwerp
Systemmanager Anet

Phone: +32 3 820.21.53
Fax: +32 3 820.21.59
GSM: 0478/36.76.28
Email: (e-mail address removed)
================================================================
 
D

Duncan Booth

Richard Philips said:
Consider the script:

def test(drivers={}):
if drivers:
print drivers
else:
drivers["A"] = "B"

if __name__ == "__main__":
test()
test()

prints in stdout:
{'A': 'B'}

I expected that nothing would be displayed.
I do not understand this behaviour (python2.3 on WinXP and Linux).

You are not alone, this is one of the commonest questions from beginners.
If anybody can explain this situation, you are welcome.

The best explanation I know is in the FAQ, entry 4.21.

See http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects
Thank you.
You are welcome.
 
J

Jay O'Connor

Richard said:
Consider the script:

def test(drivers={}):
if drivers:
print drivers
else:
drivers["A"] = "B"

if __name__ == "__main__":
test()
test()

prints in stdout:
{'A': 'B'}

I expected that nothing would be displayed.
I do not understand this behaviour (python2.3 on WinXP and Linux).

If anybody can explain this situation, you are welcome.


That caught me by suprise to, especially because after running it,
'drivers' is not defined
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top