Skip to content

Instantly share code, notes, and snippets.

@cwgem
Created February 12, 2017 22:45
Show Gist options
  • Select an option

  • Save cwgem/f424c12396bf2a7ed0df8e1ae6a5e3b0 to your computer and use it in GitHub Desktop.

Select an option

Save cwgem/f424c12396bf2a7ed0df8e1ae6a5e3b0 to your computer and use it in GitHub Desktop.
Python and default keyword args fun
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> # Let's make a function!
... def myfunc(value,mylist=[]):
... mylist.append(value)
... print(mylist)
...
>>> # Now let's run it a few times!
... myfunc(1)
[1]
>>> myfunc(2)
[1, 2]
>>> myfunc(3)
[1, 2, 3]
>>>
>>> # ???? mylist is keeping track of the values? Okay uh let's clear it out and try again
... myfunc(4, [])
[4]
>>> myfunc(5)
[1, 2, 3, 5]
>>>
>>> # It's *still* keeping track of it. Apparently it's keeping track of it here:
... # python 2 I believe is myfunc.func_defaults
... myfunc.__defaults__
([1, 2, 3, 5],)
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment