answers.py v0.0.1 - source

Peter Otten __peter__ at web.de
Thu Dec 28 08:10:27 EST 2006


Marc 'BlackJack' Rintsch wrote:

> >     def __init__(self,answers={}):
> >         self.answers=answers
> 
> Default arguments are only evaluated once when the ``def`` is executed,
> so all your `Storage` classes share the same dictionary.  One idiom to
> solve this is:
> 
>     def __init__(self, answers=None):
>         self.answers = answers or dict()

Nitpick: the expression 'answers or dict()' is false economy. It may provoke
even subtler errors, because an empty dict is False in a boolean context.
Example:

# here the answers are shared:
shared_answers = {"question": "answer"}
first = Storage(shared_answers)
second = Storage(shared_answers)
print second.answers is first.answers # True

# here the answers aren't shared:"
shared_answers = {}
first = Storage(shared_answers)
second = Storage(shared_answers)
shared_answers["question"] =  "answer"
print second.answers is first.answers # False

To avoid the confusion I recommend the following:

def __init__(self, answers=None):
    if answers is None: 
        answers = {}
    self.answers = answers

Peter



More information about the Python-list mailing list