"once" assigment in Python

Steve Holden steve at holdenweb.com
Mon Sep 17 19:48:16 EDT 2007


Lorenzo Di Gregorio wrote:
> On 17 Sep., 16:54, Larry Bates <larry.ba... at websafe.com> wrote:
>> IMHO variables like what you describe are really data not program variables.
>> You might consider putting variables like these in a dictionary and then check
>> to see if the keys exist before assignment:
>>
>> var_dict={}
>>
>> #
>> # See if 'varname' initialized, if not it needs to be
>> #
>> if 'varname' not in var_dict:
>>       var_dict[varname]=somevalue
> 
> This is a good point!
> 
> I could write something like:
> 
> instantiate('component',function)
> 
> and have instantiate() to conditionally do:
> 
> instance['component']=Module(function)
> 
> Of course this means using:
> 
> instance['component'].method()
> 
> instead of just:
> 
> component.method()
> 
Well, you could do that. Or you could define a class, with a __getattr__ 
that returns the required default value in the case where no setting had 
been made.

Then you can assign components (with their own hierarchies) to the 
attributes of your top-level design ...

> A more annoying difficulty is with the fact that, while the scope of
> ordinary variables is limited (function, package), the scope of
> 'component' would be global (the whole instance[]): having global
> names could be pretty annoying in modeling a hierarchy.  Anyway, some
> scoping mechanism could be implemented over the global dictionary and
> this could be a good price to pay to avoid other tricks.
> Further suggestions?
> 
It's not actually that hard to create objects that allow you to access 
their attributes using *either* attribute or indexing notation.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list