local variable referenced before assignment

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 6 03:48:20 EDT 2010


On Mon, 05 Apr 2010 10:08:51 -0700, John Nagle wrote:

> Alf P. Steinbach wrote:
> 
>> Best is however to recognize that you have some state (your variable)
>> and some operations on that state (your callback), and that that is
>> what objects are all about. I.e. wrap your logic in a class. Then
>> 'lastModifiedTime' becomes an instance attribute, and 'handler' becomes
>> a method.
>> 
>> It doesn't matter that there will only ever be one object (instance) of
>> that class.
>> 
>> Classes were meant for just this sort of thing, state + operations.
> 
>     Yes.  Functions with persistent state are generally a bad idea.


Persistent state is generally a bad idea, unless you need it. If you 
think you need it, you probably don't. But if you do actually need 
persistent state, it is better to hide it in some sort of routine 
(perhaps a function, perhaps a callable instance, perhaps something else) 
that can encapsulate the state, rather than store it in a global.



>     Unfortunately, the "signal" module requires a callback parameter
> which is a plain function.  So you have to send it a function, closure,
> or lambda.  Here, it's being sent a closure - "handler" bound to the
> state that existed when "signal.signal" was called.


Help on built-in function signal in module signal:

signal(...)
    signal(sig, action) -> action

    Set the action for the given signal.  The action can be SIG_DFL,
    SIG_IGN, or a callable Python object.  [...]


Doesn't seem like there is any requirement for it to be a regular 
function. Anything callable with the right signature should work, and if 
it doesn't, that's a bug.



-- 
Steven



More information about the Python-list mailing list