r/learnpython • u/zaphodikus • 3d 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?
0
Upvotes
10
u/SuntailHawk 3d ago edited 2d 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.
2
u/danielroseman 3d 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.
2
u/Outside_Complaint755 3d ago
Use name mangling:
Output:
1
u/DanceHackRock 2d 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/Fred776 3d ago
Can you give an example of what you are afraid of doing accidentally?
My general thought would be to write code that is as simple and clean as you are able to, using unit tests to thoroughly test it and help you to refactor as necessary.
1
u/TheRNGuy 3d ago
Have some abstract class, inherit 1or 2 times from it, after that use composition.
I think long inheritance chains is an anti-pattern.