Created
November 28, 2012 02:44
-
-
Save squirly/4158709 to your computer and use it in GitHub Desktop.
An inheritable lazy class with argument attachment.
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
def import_class(import_string, *a, **k): | |
module, klass = import_string.rsplit('.', 1) | |
def combine_args_kwargs(args, kwargs): | |
new_args = a + args | |
new_kwargs = k.copy() | |
new_kwargs.update(kwargs) | |
return new_args, new_kwargs | |
def load_class(): | |
return getattr(__import__(module, fromlist=[klass]), klass) | |
class lazy_class(object): | |
def __new__(cls, *args, **kwargs): | |
args, kwargs = combine_args_kwargs(args, kwargs) | |
klass_obj = cls.as_class() | |
return klass_obj(*args, **kwargs) | |
class __metaclass__(type): | |
def __new__(cls, *args, **kwargs): | |
klass_obj = getattr(__import__(module, fromlist=[klass]), klass) | |
def __init__(self, *args, **kwargs): | |
args, kwargs = combine_args_kwargs(args, kwargs) | |
klass_obj.__init__(self, *args, **kwargs) | |
return type(import_string, (klass_obj,), {'__init__': __init__}) | |
return lazy_class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment