[Tutor] set locals

spir denis.spir at gmail.com
Tue Dec 17 16:52:25 CET 2013


Hello,

is it at all possible to set new vars (or any symbol) into an existing scope 
(typically locals())?

     scope[name] = value
raises by me an error like:
     TypeError: 'mappingproxy' object does not support item assignment

I guess 'mappingproxy' is the implementation name of a scope (here, local), and 
I thought scopes were just dicts; so what is the issue? Do you see an alternative?

Context: This is used in a tool func that names defined objects of a given 
(matching patterns) in a given scope (which forms a grammar/parser). The base 
issue is that objects don't know their names, which in my case (and many more) 
are useful, in fact necessary, for programmer feedback, testing, debugging and 
more. However, at times a developper needs variants of a given pattern (matching 
same format, eg name=symbol), but they should be distinct objects: meaning copy, 
meaning setting the new variant into the scope.

The tool func (a static method of Pattern, in fact), is just:

     def name (scope):
         ''' Name all defined patterns of a given grammar's scope.
             [... more doc ...]
         '''
         for name, pat in scope.items():
             if isinstance(pat, Pattern):
                 # Just name pat:
                 pat.name = name

             # ... plus detail ...


But the body should be:

         for name, pat in scope.items():
             if isinstance(pat, Pattern):
                 # Possibly make copy in case pat is already named:
                 if pat.name:
                     new_pat = copy(pat)
                     new_pat.name = name
                     scope[name] = new_pat	# error ***
                 # Else, just name pat:
                 else:
                     pat.name = name

             # ... plus detail ...

I'm blocked. Users can do it by hand, but it's pretty annoying and a sure source 
of bugs (there is more than just naming: if users define a variant, they 
probably want to define a different match action: if no copy, then the action is 
set on the original pattern...). This should be automagic.

Denis


More information about the Tutor mailing list