Created
November 18, 2012 07:43
-
-
Save Suor/4104029 to your computer and use it in GitHub Desktop.
Classes as namespaces in python
This file contains hidden or 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
class checks(namespace): | |
immutable = lambda old_value, new_value: old_value == new_value | |
def gte(other): | |
if callable(other): | |
return lambda value: value >= other() | |
else: | |
return lambda value: value >= other | |
# These are plain functions: | |
checks.immutable | |
checks.gte(0) | |
checks.gte(datetime.now) |
This file contains hidden or 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
class namespace_meta(type): | |
def __new__(cls, name, bases, attrs): | |
attrs = dict((name, staticmethod(value) if callable(value) else value) | |
for name, value in attrs.items()) | |
return super(namespace_meta, cls).__new__(cls, name, bases, attrs) | |
class namespace(object): | |
__metaclass__ = namespace_meta |
This file contains hidden or 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 funcy import walk_values, iffy | |
class namespace_meta(type): | |
def __new__(cls, name, bases, attrs): | |
attrs = walk_values(iffy(callable, staticmethod), attrs) | |
return super(namespace_meta, cls).__new__(cls, name, bases, attrs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment