Where do nested functions live?

Frederic Rentsch anthra.norell at vtxmail.ch
Tue Oct 31 06:06:10 EST 2006


Rob Williscroft wrote:
> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python-
> list at python.org in comp.lang.python:
>
>   
>>    def increment_time (interval_ms):
>>       outer weeks, days, hours, minutes, seconds, mseconds   # 'outer' 
>> akin to 'global'
>>       (...)
>>       mseconds = new_ms - s * 1000        # Assignee remains outer
>>       m, seconds = divmod (s, 60)
>>       h, minutes = divmod (m, 60)
>>       d, hours = divmod (h, 24)
>>       weeks, days = divmod (d, 7)         # No return necessary
>>
>> The call would now be:
>>
>>    increment_time (msec)                  # No reassignment necessary
>>
>>
>> Hope this makes sense
>>     
>
> Yes it does, but I prefer explicit in this case:
>
> def whatever( new_ms ):
>   class namespace( object ):
>     pass
>   scope = namespace()
>
>   def inner():
>     scope.mseconds = new_ms - s * 1000       
>     m, scope.seconds = divmod (s, 60)
>     h, scope.minutes = divmod (m, 60)
>     d, scope.hours = divmod (h, 24)
>     scope.weeks, scope.days = divmod (d, 7)        
>
>   

This is interesting. I am not too familiar with this way of using 
objects. Actually it isn't all that different from a list, because a 
list is also an object. But this way it's attribute names instead of 
list indexes which is certainly easier to work with. Very good!

> The only thing I find anoying is that I can't write:
>
>   scope = object()
>  
> Additionally if appropriate I can refactor further:
>
> def whatever( new_ms ):
>   class namespace( object ):
>     def inner( scope ):
>       scope.mseconds = new_ms - s * 1000       
>       m, scope.seconds = divmod (s, 60)
>       h, scope.minutes = divmod (m, 60)
>       d, scope.hours = divmod (h, 24)
>       scope.weeks, scope.days = divmod (d, 7)    
>
>   scope = namespace()
>   scope.inner()
>
> In short I think an "outer" keyword (or whatever it gets called)
> will just add another way of doing something I can already do,
> and potentially makes further refactoring harder.
>
>   

Here I'm lost. What's the advantage of this? It looks more convoluted. 
And speaking of convoluted, what about efficiency? There is much talk of 
efficiency on this forum. I (crudely) benchmark your previous example 
approximately three times slower than a simple inner function taking and 
returning three parameters. It was actually the aspect of increased 
efficiency that prompted me to play with the idea of allowing direct 
outer writes.

> Thats -2 import-this points already.
>
>   

Which ones are the two?

> Rob.
>   

Frederic





More information about the Python-list mailing list