Message280025
While using decorators in python 3.5.2, I ran into a surprising bug where the decorator sometimes lost context of the outer scope. The attached file demonstrates this problem.
In this file, we have 2 decorators. They are identical, except that the first has one line (at line 11) commented out.
When I run the program, I get the following output:
dev:~/dev/route105/workspace/ir/play$ python bug.py
Trying dec1:
in dec1: {'tags': ['foo:1'], 'name': 'foo'}
inside dec1.decorator: {'tags': {'tags': ['foo:1', ['name:subsystem']], 'name': 'foo'}, 'func': <function f1 at 0x7ff03d60cb70>}
Trying dec2:
in dec2: {'tags': ['foo:1'], 'name': 'foo'}
inside dec2.decorator: {'func': <function f2 at 0x7ff03d60cc80>}
Traceback (most recent call last):
File "bug.py", line 42, in <module>
@dec2(name="foo", tags=["foo:1"])
File "bug.py", line 27, in decorator
name = tags["name"]
UnboundLocalError: local variable 'tags' referenced before assignment
There are two issues here:
1) In dec1, the keyword argument 'name' exists in the outer scope, but not in the inner scope. For some reason, the keyword argument 'tags' exists in both scopes.
2) In dec2, Adding the line
tags=tags["tags"]
causes the keyword argument 'tags' to disappear from the inner scope.
The only thing I could think of was a compiler or optimizer bug. |
|
Date |
User |
Action |
Args |
2016-11-03 21:49:41 | Brian Smith | set | recipients:
+ Brian Smith |
2016-11-03 21:49:41 | Brian Smith | set | messageid: <1478209781.37.0.548776330041.issue28606@psf.upfronthosting.co.za> |
2016-11-03 21:49:41 | Brian Smith | link | issue28606 messages |
2016-11-03 21:49:41 | Brian Smith | create | |
|