Issue 1427789: List not initialized if used as default argument (original) (raw)

This issue has been migrated to GitHub: https://github.com/python/cpython/issues/42877

classification

Title: List not initialized if used as default argument
Type: Stage:
Components: Interpreter Core Versions: Python 2.4

process

Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: dstanek, georg.brandl, goodger, griminventions
Priority: normal Keywords:

Created on 2006-02-08 18:55 by griminventions, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (5)
msg27463 - (view) Author: Jason (griminventions) Date: 2006-02-08 18:55
class A( object ): def __init__( self, someList = [] ): self.someList = someList if __name__ == "__main__": for i in range( 10 ): a = A() a.someList.append( "abc" ) print a.someList Instead of each instance of A getting an empty list, it is somehow the same list as the previous instance of A. It will not occur with the following change: class A( object ): def __init__( self ): self.someList = [] I'm using Windows XP, Python 2.4.1. jason@griminventions.com
msg27464 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-02-08 19:13
Logged In: YES user_id=1188172 This is intended behavior. Default values for function arguments are only evaluated once, so it's not advisable to use mutables there. Use None as default and create your empty list within the constructor if None is given, as in your second example.
msg27465 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-02-08 19:13
Logged In: YES user_id=1188172 This is intended behavior. Default values for function arguments are only evaluated once, so it's not advisable to use mutables there. Use None as default and create your empty list within the constructor if None is given, as in your second example.
msg27466 - (view) Author: David Goodger (goodger) (Python committer) Date: 2006-02-08 19:15
Logged In: YES user_id=7733 This is not a bug. Default values are evaluated when the "def" statement is evaluated, at compile time. See http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects
msg27467 - (view) Author: David Stanek (dstanek) Date: 2006-02-08 19:18
Logged In: YES user_id=260643 This is actually correct behavior. See the "Important Warning" in this section of the tutorial: http://docs.python.org/tut/node6.html#SECTION006710000000000000000
History
Date User Action Args
2022-04-11 14:56:15 admin set github: 42877
2006-02-08 18:55:33 griminventions create