I know python functions are virtual by default. Let’s say I have this:
class Foo: def __init__(self, args): do some stuff def goo(): print 'You can overload me' def roo(): print 'You cannot overload me'
I don’t want them to be able to do this:
class Aoo(Foo): def roo(): print 'I don't want you to be able to do this'
Is there a way to prevent users from overloading roo()?
You can use a metaclass:
The metatype’s new is called whenever a subclass is created; this will cause an error in the case you present. It will accept a definition of roo only if there are no base classes.
You can make the approach more fancy by using annotations to declare which methods are final; you then need to inspect all bases and compute all final methods, to see whether any of them is overridden.
This still doesn’t prevent somebody monkey-patching a method into a class after it is defined; you can try to catch these by using a custom dictionary as the classes’ dictionary (which might not work in all Python versions, as classes might require the class dictionary to be of the exact dict type).