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

Roy Smith roy at panix.com
Fri Dec 23 11:15:33 EST 2011


In article <4ef4a30d$0$29973$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> The disadvantage of late binding is that since the expression is live, it 
> needs to be calculated each time, even if it turns out to be the same 
> result. But there's no guarantee that it will return the same result each 
> time: consider a default value like x=time.time(), which will return a 
> different value each time it is called

I know this is not quite the same thing, but it's interesting to look at 
what django (and mongoengine) do in their model definitions, prompted by 
your time.time() example.  You can do declare a model field something 
like:

class Foo(models.Model):
   timestamp = DateTimeField(default=datetime.utcnow)

Now, when you create a Foo, if you don't supply a timestamp, it 
generates one by calling utcnow() for you.  Very handy.

I'm not arguing that Python should do that, just pointing out an example 
of where late binding is nice.  Technically, that's probably not really 
late binding.  You always get the same function bound, it's just called 
each time it's used because django notices that you passed a callable.  
Maybe sort of "early binding, late calling" would be a more apt 
description, but given that python has descriptors, the line between 
data and function sometimes gets a little blurry anyway.



More information about the Python-list mailing list