Enumeration of strings and export of the constants
Emile van Sebille
emile at fenx.com
Wed Nov 10 22:19:39 CET 2010
On 11/10/2010 5:12 AM lnenov said...
> I need to enumerate a couple hundred strings to constants and export
> them to another module(s) globals.
Do they really need to be globals? Why not a constants in an
object/container that would neither pollute the global namespace nor
risk being shadowed by subsequent inadvertent name conflict?
> In the mean time I want to keep my module's namespace as clear as I can
> and I don't want to use "import *" later.
> Here is the code I intend to use:
> 1 class Apinamespace():
> 2 @staticmethod
> 3 def import_to(destination):
> 5 for name, number in Apinamespace.__dict__.items():
> 6 if (name.startswith('__') and name.endswith('__')) or name ==
> "import_to": # :)
> 7 pass
> 8 else:
> 9 setattr(destination, name, number)
> 11 class Enumerate():
> 12 def __init__(self, names, start = 0, step = 1):
> 13 enumerate_to = Apinamespace
> 15 for number, name in self.enumerate(names, start, step):
> 16 setattr(enumerate_to, name, number)
> 18 def enumerate(self, names, start = 0, step = 1):
> 19 for index in range(len(names)):
> 20 yield (start, names[index])
> 21 start += step
> 23 example_names = ['Foo','Bar','Free', 'Beer']
> 24 example_names2 = ['Foo_me_too', 'Bar_me_too', 'Free_me_too',
> 25 Enumerate(example_names)
> 26 Enumerate(example_names2, 4, 2)
> This works like a charm:
> >>> import sys, test
> >>> thismodule = sys.modules[__name__]
> >>> test.Apinamespace.import_to(thismodule)
> >>> Beer
> >>> Beer_me_too
> Is there a better and more common way to do this?
Yes -- don't. It'd generally indicate what's been called 'a bad smell'
> Do you know of a way to see the module in/from which a function was
> called without using traceback and frames? (I want to remove the
> argument from Apinamespace.import_me)
> And can line 6 be replaced by something less evil.
> Thanks for any suggestions.
More information about the Python-list