12

I'm trying to use deepcopy (from the copy module) to deeply copy a node tree from the ast module.

This doesn't seem to work. I'm getting strange errors like TypeError: required field "name" missing from FunctionDef when I use the copied result (and I checked it; it really is missing in the copied node), so it didn't correctly copied them.

Is there a trick I can make this working? Or maybe am I missing something?

Albert
  • 65,406
  • 61
  • 242
  • 386
  • With the question like this, it is a guessing game. There are generally no "tricks" please post your relevant code. – Trufa Jul 21 '11 at 14:42
  • 2
    I think this is a good question, and perfectly clear what his problem is, +1. – agf Jul 21 '11 at 14:53
  • 3
    @agf: I removed my down-vote just in case. It seems I was wrong about it due to my lack of technical knowledge on the subject, maybe it just looks like a vague question, if that is the case, my apologies to Albert. – Trufa Jul 21 '11 at 15:45

1 Answers1

11

Sorry, I was wrong. copy.deepcopy seems to work correct. The reason I thought it wouldn't work is because of this very odd behavior:

import ast, copy
n = ast.FunctionDef(
        name=None,
        args=ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]),
        body=[], decorator_list=[])
n.name = "foo"
ast.fix_missing_locations(n)
n = copy.deepcopy(n)
print n.name

This returns None in PyPy. Probably a bug because in CPython 2.6, I get foo. Strangely, in PyPy, if I remove name=None from the ast.FunctionDef call, I also get foo as the output.

I created a bug report for PyPy about this.

Albert
  • 65,406
  • 61
  • 242
  • 386