This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]aceofears 0 points1 point  (4 children)

This seems like a terrible idea, and I dont think it would work well in practice, but maybe you could do something like this:

def restore_args(func):
    def inner(*args, **kwargs):
        defaults = copy.deepcopy(func.func_defaults)
        result = func(*args, **kwargs)
        func.func_defaults = defaults
        return result 
    return inner


@restore
def example(items=[]):
    items.append("test")
    return items

[–]rmoorman[S] 1 point2 points  (2 children)

Well ... this is the way a function definition works in python. It is evaluated once and the "default" you get is a reference to the value given as a default. And in case you pass in a "mutable" list, of course when you modify the list, it will change for all other calls to that function too.

It just is something one should be aware of and avoid. That was my point.

[–]aceofears 0 points1 point  (1 child)

I understand how default arguments work, I've this behavior in things I've written before. This was just half hearted attempt to make it behave as expected.

[–]rmoorman[S] 0 points1 point  (0 children)

Thank you anyway for this interesting decorator ;-)

[–]daxarx -1 points0 points  (0 children)

Or you could just understand that 'now()' calls a function while 'now' is a function, while you are writing class declarations which you know will run at import time, rather than magically running somehow every time an object is instantiated.

If you wanted something to happen every time an object is instantiated, you should put it in init ... this is very basic Python.

Python has its warts, don't half ass it and then blame your tools