Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: deeply copy ast node tree

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?

like image 300
Albert Avatar asked Jul 21 '11 14:07

Albert


People also ask

How do you make a deep copy in Python?

To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.

How do you copy a node in Python?

You can just use copy. deepcopy() to make a copy of the element. (this will also work with lxml by the way).

Is list copy deep copy?

You don't make a deep copy using list() . (Both list(...) and testList[:] are shallow copies.) You use copy.

How do you deep copy an array in Python?

Use the copy. deepcopy() Function to Deep Copy a List in Python. The deepcopy() function from the copy module is used to create a deep copy of the list specified. If we alter this copy, then the contents of the original list remain the same and are not changed.


1 Answers

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.

like image 127
Albert Avatar answered Sep 17 '22 21:09

Albert