Skip to content
Advertisement

Adding dynamic attribute to python class fails

I’m trying to dynamically add an attribute to some class from javalang:

In [1]: import javalang
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
In [3]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)

But when I try to simply assign a new attribute (qualifier_type)

In [4]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"

Nothing happens:

In [5]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)

Advertisement

Answer

Apparently, my attribute was there all the time, it just wasn’t printed, since the __repr__ implementation iterated over self.attrs.

In [1]: import javalang
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
In [3]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"
In [4]: print(tree.types[0].body[0].declarators[0].initializer.qualifier_type)
DDD

Explicitly adding my attribute, I can now print my class (scroll to the right to see it)

In [5]: tree.types[0].body[0].declarators[0].initializer.attrs += ("qualifier_type",)
In [6]: print(tree.types[0].body[0].declarators[0].initializer)
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, qualifier_type=DDD, selectors=[], type_arguments=None)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement