Can global variable be passed into Python function?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 1 02:59:56 CET 2014


On Sat, 01 Mar 2014 03:06:38 +0200, Marko Rauhamaa wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> 
>> I can only imagine you mean something like this:
>>
>> class Outer:
>>     class InnerOne:
>>         ...
>>
>>     class InnerTwo:
>>         ...
>>
>>     class InnerThree:
>>         ...
>>
>>
> No, I mean this:
> 
>    class StateMachine:
>        def __init__(self):
>             sm = self
> 
>             class Idle:
>                 def connect(self):
>                     ...
>                     sm.set_state(Connecting)
>                     ...
[...]


Ah, interesting. You're not just using the classes as symbols, you 
actually are giving them behaviour and using a State pattern.

But I'm not sure that there is a good reason to put the class definitions 
inside the __init__ method. That means every time you create a new 
StateMachine instance, the classes have to be re-created. (That might be 
a feature if you intend for instance1.IDLE != instance2.IDLE, but I don't 
see any good reason for that.)

It will be much more efficient if you pull all the Idle, etc. classes out 
and make them top-level global classes. Or at least stick them inside the 
StateMachine class, which means that they only get created once, and are 
shared between all StateMachine instances. But then the closure over sm 
won't work... I'll need to think some more about that.

However, the example as given won't quite work. You never instantiate the 
Idle etc. classes, which means the methods won't work. You need to make 
them class methods or static methods, or perform some metaclass magic 
prevent them from being turned into instance methods when called.

Since in this example you've actually got significant behaviour in the 
states, they aren't just symbols, and some sort of solution along these 
lines (whether you use multiple inner classes or not) is appropriate.


-- 
Steven



More information about the Python-list mailing list