Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Alexei-Kornienko/90147f5acbf6af1d6df9477b2760c96a to your computer and use it in GitHub Desktop.
Save Alexei-Kornienko/90147f5acbf6af1d6df9477b2760c96a to your computer and use it in GitHub Desktop.
class StateGuard(type):
def __new__(cls, name, bases, dct):
base_states = [base for base in bases if type(base) == cls]
if len(base_states) > 1:
raise TypeError("Multiple inheritance of States is not allowed")
elif len(base_states) == 1:
state = base_states.pop()
state_methods = {method for method in dir(state) if not method.startswith('__')}
for b in bases:
if b == state:
continue
base_methods = {method for method in dir(b) if not method.startswith('__')}
overrides = base_methods & state_methods
if overrides:
raise TypeError(f'Class {b} overrides methods {overrides} from {state}. This is not allowed')
return super().__new__(cls, name, bases, dct)
class BaseState(metaclass=StateGuard):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment