initializing "parameters" class in Python only once?

alex23 wuwei23 at gmail.com
Thu Jul 17 05:35:24 CEST 2014


On 15/07/2014 3:28 PM, Steven D'Aprano wrote:
> # === module params.py ===
> class Params(object):
>      a = 1
>      b = 2
>
>      @property
>      def c(self):
>          return self.a**2 + self.b**2 - self.a + 1
>
> params = Params()
> del Params  # hide the class
>
>
> Then callers just say:
>
> from params import params
> print params.c

I'd replace the instantiation & deletion of the class in params.py with:

     import sys
     sys.modules[__name__] = Params()

..and replace the module itself with the parameter object. I'd also add:

     __file__ = __file__

...to the class definition to help with debugging. But this is really 
just bikeshedding.

It's a shame the property decorator doesn't work at the module level, 
though.




More information about the Python-list mailing list