[Python-ideas] Mutable default arguments - another approach
Piotr Duda
duda.piotr at gmail.com
Wed Jan 31 14:19:06 CET 2007
2007/1/31, Chris Rebert <cvrebert at gmail.com>:
> Piotr Duda wrote:
> > Read my previous post again, and give me examples of what you cannot
> > do regarding default arguments.
>
> First, I'd like to register my dislike for implicitly determining when a
> default argument will be copied on every call.
In my solution you can always declare this explicitly.
Only problem here is to determine which objects are copied, simplest
rule here is to copy all object except instances of built-in immutable
types.
>
> Second, as per your request:
>
> def foo(bar=None):
> if bar is None: bar = function_call()
> #code
>
> def foo(bar=None):
> if bar is None: bar = something.method_call()
> #code
In my solution you can do both.
Assuming there are all classes/methods defined in my first post, use:
@DefaultArgWrapper
def calldefarg(callable): #this function should be defined in stdlib
while 1:
yield callable()
first example
def foo(bar = calldefarg(function_call)):
#code
here i assume that function_call is available at definition call, if
it isn't then use this
def foo(bar = calldefarg(lambda: function_call())):
#code
and the second example
def foo(bar = calldefarg(something.method_call)):
#code
or if something isn't available at definition time
def foo(bar = calldefarg(lambda: something.method_call())):
#code
there's one restriction, that 'something' cannot depend on other
function argument(s).
> #These were just a few. There are others.
>
> These cannot be rewritten using simple copying decorators. Various
> decorators have been presented that account for some of these (and
> other) situations. However, IMHO they're not too elegant/clean. Thus, a
> slightly more sophisticated solution is required.
Are you referring here to my solution?
--
闇に隠れた黒い力
弱い心を操る
More information about the Python-ideas
mailing list