[Python-Dev] nonlocals() function? (original) (raw)
Steven D'Aprano steve at pearwood.info
Mon Apr 5 01:44:57 CEST 2010
- Previous message: [Python-Dev] nonlocals() function?
- Next message: [Python-Dev] nonlocals() function?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Mon, 5 Apr 2010 09:03:17 am average wrote:
On Sat, Apr 3, 2010 at 6:31 AM, Nick Coghlan <ncoghlan at gmail.com> wrote: > Steve Bonner wrote: >> What do we think of adding a built-in nonlocals() function that >> would be similar to globals() and locals()? Like those functions, >> it would return a dictionary of variable names and their values. >> Since we now have the nonlocal statement, it would be consistent >> to keep the three scopes local/nonlocal/global with parallel >> capabilities. And it might sometimes be useful for code inside a >> nested function to see what variables are available at the >> enclosing level. > > That isn't as easy as it may sound. locals() and globals() are each > single namespaces, while the nonlocals may actually span multiple > namespaces.
This is probably is way off, but why not use sets. It seems that these special "functions" (which actually don't do any transformations) should be properties or attributes, and in any case would be better served by returning (holding) sets, then one could do standard set operations on them (including the set difference operations upon the set named "locals").
globals() and locals() return dicts mapping names to objects. Returning sets would break code that expects a dict, as well as reducing functionality: they could return the object names, but not the objects themselves. That makes it unobvious how to get to the objects, given the name. (Using eval perhaps?)
I'm not sure why you think that the globals() and locals() functions aren't functions. They transform the empty argument into dicts. You say they should be properties and attributes, but properties of what?
These old functions predate the introductions of attributes/properties and sets, and like anything that is sure to be a group containing no duplicates, it should really return a set to remove the ambiguity to the programmer (unlike returning a list as is presently). That includes dir() too and probably others.
You are confused -- globals() and locals() don't return lists.
Bringing this back to the original question, I very rarely use globals() and even more rarely use locals(), so I don't have much need for a nonlocals() function. I suspect it's a solution in search of a problem, but the same holds for locals() (in my option) and so I wouldn't object if somebody else volunteered to do the work :)
+0
-- Steven D'Aprano
- Previous message: [Python-Dev] nonlocals() function?
- Next message: [Python-Dev] nonlocals() function?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]