This should be a simple question...

Tim Chase python.list at tim.thechases.com
Fri Mar 6 10:17:31 EST 2009


> 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")





More information about the Python-list mailing list