Last active
September 9, 2020 10:24
-
-
Save rednafi/80a7dff6cd7f7bbb0c144085d32da668 to your computer and use it in GitHub Desktop.
Metaclass to apply staticmethod decorator to all the methods of a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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