Hi,

I need to enumerate a couple hundred strings to constants and export them to another module(s) globals. 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:

    test.py
  1 class Apinamespace():
  2     @staticmethod
  3     def import_to(destination):
  4
  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)
 10
 11 class Enumerate():
 12     def __init__(self, names, start = 0, step = 1):
 13         enumerate_to = Apinamespace
 14
 15         for number, name in self.enumerate(names, start, step):
 16             setattr(enumerate_to, name, number)
 17
 18     def enumerate(self, names, start = 0, step = 1):
 19         for index in range(len(names)):
 20             yield (start, names[index])
 21             start += step
 22
 23 example_names = ['Foo','Bar','Free', 'Beer']
24 example_names2 = ['Foo_me_too', 'Bar_me_too', 'Free_me_too', 'Beer_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
3
>>> Beer_me_too
10

Is there a better and more common way to do this?
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.

Lyudmil



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to