Early and late binding [was Re: what does 'a=b=c=[]' do]

Chris Angelico rosuav at gmail.com
Fri Dec 23 10:55:41 EST 2011


On Sat, Dec 24, 2011 at 2:49 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> To fake early binding when the language provides late binding, you still
> use a sentinel value, but the initialization code creating the default
> value is outside the body of the function, usually in a global variable:
>
>    _DEFAULT_Y = []  # Private constant, don't touch.
>
>    def func(x, y=None):
>        if y is None:
>            y = _DEFAULT_Y
>        ...
>
> This separates parts of the code that should be together, and relies on a
> global, with all the disadvantages that implies.

A static variable (in the C sense) would make this just as clean as
the alternative. In Python, that could be implemented as an attribute
of the function object. Oh looky here... that's how default arguments
are implemented. :)

Tim Toady.

ChrisA



More information about the Python-list mailing list