Default Value

Rick Johnson rantingrickjohnson at gmail.com
Thu Jun 20 14:05:32 EDT 2013


On Thursday, June 20, 2013 10:38:34 AM UTC-5, Chris Angelico wrote:
> Function defaults in Python, being implemented as
> attributes on the function object, are very similar in
> nature to static variables in C.

Oh wait a minute. i think it's becoming clear to me now!

Python functions are objects that take arguments, of which
(the arguments) are then converted to attributes of the
function object. Ah-Ha! Urm, but wait! We already have a
method to define Objects. Heck, I can even create my own
callable objects if i want! 

Observe:
  py> class FuncAdd(object):
  ...     def __init__(self, ivalue):
  ...         self.ivalue = ivalue
  ...     def __call__(self, numeric):
  ...         return self.ivalue + numeric
  ...
  py> fa = FuncAdd(10)
  py> fa(10)
  20
  py> fa(20)
  30

I can even emulate (quite easily) this idea of
"persistence of function arguments" with mutables 
too, Yippee!

  py> class ArgPersist(object):
  ...     def __init__(self, lst):
  ...         self.lst = lst
  ...     def __call__(self, arg):
  ...         self.lst.append(arg)
  ...         return self.lst
  ...         
  py> fp = ArgPersist([1,2,3])
  py> fp(4)
  [1, 2, 3, 4]
  py> fp([5,6,7])
  [1, 2, 3, 4, [5, 6, 7]]
  
But then, i can even do it WITHOUT creating an object
definition:

  py> mutable = []
  py> def expandMutable(arg):
  ...     mutable.append(arg)
  ...     
  py> expandMutable(1)
  py> mutable
  [1]
  py> expandMutable([2,3,4])
  py> mutable
  [1, [2, 3, 4]]

ANY of those approaches are much less confusing than the
current flaw and do not violate the least astonishment law..
I'm quite Okay with Python functions being first class
objects, however, i am not okay with violating the
fundamental nature of subroutines, especially when that
violation can offer no clear and arguable benefits and is in
fact unreasonably esoteric in nature.



More information about the Python-list mailing list