Why use Slot? from Peter Norvig's AI code

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Dec 4 07:11:04 EST 2007


Davy a écrit :
> Hi all,
> 
> When reading Python source code of Peter Norvig's AI book, I found it
> hard for me to understand the idea of slot (function nested in
> function). 

First point : this code seems to be based on an older (way older) Python 
version, so some things would not be done that way no more. Also, in 
newer (well... not that new, but...) Python versions, the term 'slot' 
has a quite different meaning (for short: a memory optimization for 
attributes...). FWIW, what the author names 'slots' here are really 
instance attributes - not the use of inner functions (please refer to 
the class's docstring and __init__ method code).

> Please see "program()" nested in "make_agent_program()",
> why not use program() directly?

It's a local variable of make_agent_program, so unless you bind it to 
another name (which is done in the __init__), you can't access it from 
outside make_agent_program.

The intent - which is explained in the docstring - is to make sure the 
'program' function won't access the Agent instance - so it was obviously 
written for a Python version that predates lexical closures support (you 
can do some archeological research to find out when this support was 
added if you want !-).

Now this implementation, whatever it was worth by the time this code was 
written (some 5 or more years ago AFAICT) would be considered a WTF with 
newer Python versions - where the obvious solution would be to define 
"program" as a staticmethod.



HTH



More information about the Python-list mailing list