class checking its own module for an attribute

R

Rod Person

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top