Skip to content

Instantly share code, notes, and snippets.

@rednafi
Last active September 9, 2020 10:24
Show Gist options
  • Save rednafi/80a7dff6cd7f7bbb0c144085d32da668 to your computer and use it in GitHub Desktop.
Save rednafi/80a7dff6cd7f7bbb0c144085d32da668 to your computer and use it in GitHub Desktop.
Metaclass to apply staticmethod decorator to all the methods of a class
from types import FunctionType
class StaticMeta(type):
def __new__(cls, name, bases, attrs):
"""Metaclass to apply staticmethod decorator to all the methods."""
new_cls = super().__new__(cls, name, bases, attrs)
# key is attribute name and val is attribute value in the attrs dict
for key, val in attrs.items():
if isinstance(val, FunctionType) and not key.startswith("__"):
setattr(new_cls, key, staticmethod(val))
return new_cls
class Foo(metaclass=StaticMeta):
def __init__(self):
pass
def bar():
return "Look Ma! No self in this method"
foo = Foo()
assert foo.bar() == "Look Ma! No self in this method"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment