Skip to content

Instantly share code, notes, and snippets.

@msullivan
Created October 25, 2018 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msullivan/dddcf35fddd83ad3a6a31da18c338278 to your computer and use it in GitHub Desktop.
Save msullivan/dddcf35fddd83ad3a6a31da18c338278 to your computer and use it in GitHub Desktop.
python static methods that can't be called on objects
from types import MethodType
class strict_staticmethod:
def __init__(self, f):
self.f = f
def __get__(self, obj, type=None):
if obj is not None:
raise AttributeError("strict_staticmethod can't be accessed through obj")
return self.f
class strict_classmethod:
def __init__(self, f):
self.f = f
def __get__(self, obj, type=None):
if obj is not None:
raise AttributeError("strict_classmethod can't be accessed through obj")
if type is None:
raise TypeError
return MethodType(self.f, type)
# Test
class A:
@strict_staticmethod
def foo(x):
print('foo:', x)
@strict_classmethod
def bar(cls, x):
print('bar:', cls.__name__, x)
class B(A): pass
A.foo(5)
# A().foo(5) # fails
A.bar(5)
# A().bar(5) # fails
B.bar(5)
@msullivan
Copy link
Author

(because a friend asked about it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment