state machine and a global variable

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Dec 15 04:58:50 EST 2007


On Sat, 15 Dec 2007 01:07:17 -0800, tuom.larsen wrote:

...
> later in the library I would like to expose the
> simplified interface as well:
> 
> _machine = StateMachine()
> function0 = _machine.function0
> function1 = _machine.function1
> function2 = _machine.function2
> ...
> 
> Is there a way to do so in a programmatic way? Like:
> 
> _machine = StateMachine()
> for function in {every function in _machine}:
>     function = _machine.function
> 
> Not that it's difficult to copy-paste some lines, I'm just curious and
> maybe it would be a tiny bit easier to maintain the library.

You can say:

# Untested!
_machine = StateMachine()
from new import instancemethod
for name in _machine.__class__.__dict__:
    if name.startswith('_'): continue
    obj = getattr(_machine, name)
    if type(obj) == instancemethod:
        globals()[name] = obj


but that's likely to export a bunch of functions you don't actually want. 
A better solution might be to create a class attribute containing the 
names you DO want to export, and reject everything else:

class StateMachine(object):
    _exportable = ['spam', 'eggs', 'parrot']
    # function definitions go here

for name in _machine.__class__.__dict__:
    if name in _machine._exportable:
        globals()[name] = getattr(_machine, name)



-- 
Steven



More information about the Python-list mailing list