class checking its own module for an attribute

Rod Person rodperson at rodperson.com
Wed Mar 21 16:25:03 CET 2012


We have a module called constants.py, which contains related to server
names, databases, service account users and there passwords.

In order to be able to use constants as command line parameters for
calling from our batch files I created the class below that checks to
make sure the parameter value is a valid constant and if so return it's
value.

class ConstantParameterCheck(Action):
  def __call__(self, parser, namespace, value, option_string=None):
    if value:
      if not hasattr(CCBH.constants, value):
        message = ("Invalid parameter value: {0!r}. Value must be a
		    value constant in CCBH.constants.".format(value))
raise ArgumentError(self, message)

      setattr(namespace, self.dest, getattr(CCBH.constants, value))

This works great, but it has to be placed in every script, so I decided
why not place this in the constants.py module so it can just be
imported. So I did that and got it to work like this:

class ConstantParameterCheck(Action):
  def __call__(self, parser, namespace, value, option_string=None):
    from CCBH import constants
    
    if value:
      if not hasattr(constants, value):
        message = ("Invalid parameter value: {0!r}. Value must be a
		    value constant in CCBH.constants.".format(value))
raise ArgumentError(self, message)

      setattr(namespace, self.dest, getattr(CCBH.constants, value))

The question is there a way I can do this with out having to import
constants when what it's doing is importing itself. It would seem to me
that there should be a way for a module to reference itself. In that
thinking I have tried

  if not(hasattr(__file__, value):
  if not(hasattr(__name__, value):

and even:

  this = sys.argv[0]
  if not(hasattr(this, value):

None of which works.

-- 

Rod Person  http://www.rodperson.com  rodperson at rodperson.com

'Silence is a fence around wisdom'



More information about the Python-list mailing list