Skip to content

Instantly share code, notes, and snippets.

@mdalp
Created March 4, 2016 16:53
Show Gist options
  • Save mdalp/45e380ca5e26962cd699 to your computer and use it in GitHub Desktop.
Save mdalp/45e380ca5e26962cd699 to your computer and use it in GitHub Desktop.
Weird type that automatically makes all methods of a class static.
import re
class DaveType(type):
not_allowed_attr_names = re.compile('^__\w+__$')
@classmethod
def _is_allowed_attr_name(cls, name):
return not cls.not_allowed_attr_names.match(name)
@classmethod
def _is_protected(cls, attr):
is_allowed_attr_name = cls._is_allowed_attr_name(attr.__name__)
if getattr(attr, 'exception', False):
return is_allowed_attr_name
return not is_allowed_attr_name
@classmethod
def _is_attr_valid_callable(cls, attr):
return (
hasattr(attr, '__call__') and
not cls._is_protected(attr) and
attr.__name__ != cls.__name__
)
def __new__(cls, *args, **kwargs):
for k, v in args[2].items():
if cls._is_attr_valid_callable(v):
args[2][k] = staticmethod(v)
return super(cls, cls).__new__(cls, *args, **kwargs)
class MyObject(object):
__metaclass__ = DaveType
def __init__(self, foo=None):
self.foo = foo
def my_method(foo, bar):
return foo, bar
def my_method1(self, foo, bar):
return self.foo, foo, bar
my_method1.exception = True
my_object = MyObject(1)
assert my_object.my_method(1, 2) == (1, 2)
assert my_object.my_method1(2, 3) == (1, 2, 3)
print 'Done'
@mdalp
Copy link
Author

mdalp commented Mar 4, 2016

This is a joke, NEVER USE IT!!

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