initializing "parameters" class in Python only once?

Ethan Furman ethan at stoneleaf.us
Thu Jul 17 00:43:48 EDT 2014


On 07/16/2014 08:35 PM, alex23 wrote:
> 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.

Just make sure the 'sys.modules' assignment happens at the *end* of params.py.

--
~Ethan~



More information about the Python-list mailing list