This should be a simple question...

Steve Holden steve at holdenweb.com
Fri Mar 6 11:04:39 EST 2009


Tim Chase wrote:
>> Maybe I'm missing something obvious here
>>
>> def A (...):
>> #set a bunch of variables
>>   x = 1
>>   b = 2
>>   ...
>>
>>   Do something with them
>>
>> def B (...):
>> #set the same bunch of variables
>>   x = 1
>>   b = 2
>>   ...
>>
>>   Do something with them
>>
>> I want to apply DRY, and extract out the common setting of these
>> variables into the local scope of the functions A and B.  How to do
>> this?  (Other than just setting them in the module scope)
> 
> As Diez suggests, if you don't want to litter your global namespace, use
> a class:
> 
>   class Foo:
>     x = 1
>     b = 2
>     @classmethod
>     def A(cls, *args, **kwargs):
>       do_stuff_with(Foo.x, Foo.b, args, kwargs)
>     @classmethod
>     def B(cls,*args, **kwargs):
>       do_other_stuff_with(Foo.x, Foo.b, args, kwargs)
> 
>   Foo.A(3, 1, 4)
>   Foo.B("Hello", recipient="world")
> 
That's not what classes are really for, though ...

If x and b are meant to be global than bite the bullet and *make* them
global.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
Holden Web LLC                 http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/




More information about the Python-list mailing list