Debugging decorator

Chris Angelico rosuav at gmail.com
Sun Nov 3 08:20:03 EST 2013


On Sun, Nov 3, 2013 at 9:55 PM, Jason Friedman <jsf80238 at gmail.com> wrote:
>
>> I wrote this decorator: https://gist.github.com/yasar11732/7163528
>>
> I ran it with Python 2 and thought it was neat.
> Most of my work is Python 3.
> I ran 2to3-3.3 against it and I am getting this error:
>
> $ ./simple.py
> Traceback (most recent call last):
>   File "./simple.py", line 3, in <module>
>     @debugger.debugging
>   File "/home/jason/python/debugger.py", line 41, in debugging
>     new_function_body.append(make_print_node("function %s called" %
> func.__name__))
>   File "/home/jason/python/debugger.py", line 6, in make_print_node
>     return ast.Print(dest=None, values=[ast.Str(s=s)], nl=True)
> AttributeError: 'module' object has no attribute 'Print'
>
> Comparing http://docs.python.org/2/library/ast.html#module-ast against
> http://docs.python.org/3.3/library/ast.html#module-ast I see that "Print"
> has indeed been removed.

Ah, that'd be because 'print' is no longer a statement. Check out this
function's disassembly:

def hello_world():
    print("Hello, world!")

Python 2.7:
  2           0 LOAD_CONST               1 ('Hello, world!')
              3 PRINT_ITEM
              4 PRINT_NEWLINE
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

Python 3.3:
  2           0 LOAD_GLOBAL              0 (print)
              3 LOAD_CONST               1 ('Hello, world!')
              6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

As print is now a function, you're going to need to construct a
function call element instead of a special 'print' node. I don't know
how to do that as I'm not an AST expert, but hopefully you can work it
out from there?

If you need it to be cross-version, you could probably use
sys.stdout.write explicitly (not forgetting to add a newline, which
print does and write - obviously - doesn't). Or just demand that "from
__future__ import print_function" be used, which will make 2.7 like
3.3.

ChrisA



More information about the Python-list mailing list