There's always something like:
class something(object):
def __init__(self):
import constants
for name in ['x', 'y', ...]:
setattr(self, name, getattr(constants, name))
That has the advantage of avoiding repreating self.X = constants.X
so very many times, and means you're only listing the names once in one place.
You could use this:
for name, value in constants.__dict__.iteritems():
setattr(self, name, value)
To get all the names bound in constants
without explicitly listing them, but I personally would not. It makes it much less clear what attributes something
objects actually have, and it's very easy for Python modules to end up containing more names than you realise. For example, if you have to import another module (say, math
) in constants
in the process of defining all your constants, then you'll end up with an unexpected math
attribute of all your something
instances.
I think explicitly listing the names you mean to import is clearer. Plus, it means that you don't affect all your something
instances if you discover you need to add more constants for some other part of your program to use (and if the constants can only ever have relevance to something
then they really should be listed in something
, not in an external module).