r/learnpython • u/zaphodikus • 1d ago
How to not clobber a class when inheriting
I wrote a visitor to extract some datas via the ast
class VariableFinder(ast.NodeTransformer):
""" Visitor pattern impl."""
def __init__(self, find_object:str, find_method:str):
"""
filter for only method calls that match find_object.find_method
store the line number and store the value or args passed to the call
"""
self.find_method = find_method
self.find_object = find_object
self.found = []
...
And it struck me this is not C++, so how do we stop ourselves accidentally blatting/clobbering over ast.NoteTransformer attributes? I'm missing something and my searches are all indicating that the visitor pattern is frowned upon. Is there an alternative way to do these safely?
2
u/danielroseman 1d ago
You read the documentation, or rely on a linter/type checker which will understand these things.
I don't know what you mean by "the visitor pattern is frowned upon". This is specifically a class which visits all nodes in an AST, it already uses the visitor pattern.
1
u/zaphodikus 1d ago edited 1d ago
When i google it, i started reading that it was dangerous, for the same reasons I suspected. Assuming I knew about the magic attribute re-writting was the gotcha.
1
u/FontanJanneice18 1d ago
this is pretty much why a good ide with autocomplete and type checking is mandatory once classes get even slightly complex.
2
u/Outside_Complaint755 1d ago
Use name mangling:
import ast
class VariableFinder(ast.NodeTransformer):
# Reserve the names on the class - Not strictly necessary.
__find_method = None
__find_object = None
""" Visitor pattern impl."""
def __init__(self, find_object:str, find_method:str):
"""
filter for only method calls that match find_object.find_method
store the line number and store the value or args passed to the call
"""
self.__find_method = find_method
self.__find_object = find_object
self.__found = []
print(*(n for n in dir(VariableFinder) if n.startswith("_V")), sep="\n")Output:
_VariableFinder__find_method
_VariableFinder__find_object1
u/zaphodikus 18h ago
Helpful answer, but. in order to read __found afterwards, then I have to read
_VariableFinder__foundwhich feels nasty, and took me a while to figure out.Hard to grasp for me where the trouble was, when python renamed a thing without telling you your __ dunder properties which I'm returning data via got moved. I'll have to jsut comment it better. It gets overly complicated as your rather terse piece of filtering code which basically inspects the entire object shows, just because the property name gets mangled you have to hack it with some code that not everyone can read ...urg.
What does the splatting in that last print() line there do?
1
u/Outside_Complaint755 14h ago
The print was just to output the mangled names for demonstration purposes.
if you want to access those attributes from outside of the class methods more easily you could consider making getter and setter methods or using @property
1
u/DanceHackRock 20h ago
Inheritance was an important principle for teaching OOP in the nineties. Today nobody really uses it for implementation but just for interfaces instead.
What is the actual problem you want to solve?
1
u/zaphodikus 18h ago
I'm basically looking for all lines of code that call a specific function on a specific property/variable/object instance, because I want to know what the arg passed to that call is so I can print it in a report. But it's a static, so the arg has to be a constant in reality, and the AST is nice in that it tells you if it is a constant. Very convoluted, and i did not want to accidentally clobber any state in
ast.NodeTransformer.1
u/DanceHackRock 18h ago
That is still a lot of technical detail about how you want to do something. Smells like an XY problem.
Why do you want to do it in the first place?
What actionable insights do you want to gain?
1
u/zaphodikus 17h ago edited 16h ago
I wanted a report of all runtime pytest fixtures in my own code, but not the ones defined using the @ decorator. Because i already used the ast to search for those. So I figured fixtures can be registered only in conftest.py, and using the ast to go find where I register any should be do-able. But without a lot of deep knowledge of the AST, its really a stretch to fill the gap between 'X' and 'Y' if all i want is to search for every 'append()' call made to the fixturenames collection. Its a hack, sure, but 12 lines of working code beats learning more than I have to.
My actionable insights are to work out which fixtures im not using much and which ones I can maybe retire or rewrite. So a report on all of them was my goal. (Basically a huge CTRL+SHIFT+F and a regex that I will forget very quickly and then count all occurrences. )
1
u/TheRNGuy 1d ago
Have some abstract class, inherit 1or 2 times from it, after that use composition.
I think long inheritance chains is an anti-pattern.
9
u/SuntailHawk 1d ago edited 1d ago
Python has a mechanism for avoiding attribute name collisions with inheritance - double underscore name mangling. If you do:
Then python will automatically rewrite those attribute names so
__find_objectbecomes_VariableFinder__find_object.If the parent class happened to also have__find_object, its attribute name would be_NodeTransformer__find_object. This replacement is done at compile time. Note that this won't work with names that are reserved for dunder methods, which also have a double leading underscore.This doesn't really have anything to do with the visitor pattern specifically, it's just an issue with inheritance in general in a language that has no truly private attributes. It's convention to name "private" attributes and methods with a single leading underscore, but that's just a variable name convention, and doesn't control access in a real way.