Skip to content

Instantly share code, notes, and snippets.

@meonkeys
Last active December 10, 2015 22:49
Show Gist options
  • Select an option

  • Save meonkeys/4505041 to your computer and use it in GitHub Desktop.

Select an option

Save meonkeys/4505041 to your computer and use it in GitHub Desktop.
Python Idiom - don't try to declare instance variables like you might in Java or PHP.
# I was surprised today by Python's class semantics. tl;dr is that
# "pre-declaration" (like you might do in Java or PHP) is unnecessary, and can
# lead to some unexpected results.
#
# See: https://twitter.com/meonkeys/status/289454306707521536
# and: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
# and: http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python
# and: http://stackoverflow.com/questions/68645/static-class-variables-in-python
# and: http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes
class Foo(object):
a = [] # this is a class attribute, initialized when class is declared
x = Foo()
x.a.append(7) # heads up, this modifies Foo.a
y = Foo()
print y.a # prints [7]
class Bar(object):
a = 5 # this is a class attribute, initialized when class is declared
x = Bar()
x.a = 7 # we just created an instance/data attribute with the same name
y = Bar()
print y.a # prints 5
# Foo behaved like I expected (similar to Java and PHP), but that's just
# because I didn't really understand what was going on.
# If what I really want in Foo is a data/instance attribute, I should do this
# instead:
class Foo(object):
def __init__(self):
self.a = []
# This simple Python function is the clearest example to me of this major
# difference between Python and other languages I use - default parameter
# values are initialized immediately, not when a function is called.
# (From: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables ,
# although I changed the function name from bad_append)
def static_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
>>> print static_append('one')
['one']
>>> print static_append('two')
['one', 'two']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment