Created
December 9, 2010 05:37
-
-
Save daeken/734373 to your computer and use it in GitHub Desktop.
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
import inspect | |
class MetaVar(object): | |
def __init__(self, name): | |
self.name = name | |
self.value = None | |
def __repr__(self): | |
return '_.%r' % self.name | |
class Meta(object): | |
def __getattr__(self, name): | |
return MetaVar(name) | |
def __call__(self, _obj=None, **kwargs): | |
assert (_obj != None or len(kwargs) > 0) and not (_obj != None and len(kwargs) > 0) | |
if _obj == None: | |
_obj = kwargs | |
return Pattern(_obj) | |
_ = Meta() | |
class Pattern(object): | |
def __init__(self, obj): | |
self.metavars = {} | |
self.pattern = obj | |
self.getVars(self.pattern) | |
def getVars(self, pattern): | |
if isinstance(pattern, MetaVar): | |
self.metavars[pattern.name] = pattern | |
return | |
if isinstance(pattern, dict): | |
for elem in pattern.values(): | |
self.getVars(elem) | |
else: | |
for elem in pattern: | |
self.getVars(elem) | |
def match(self, obj): | |
frame = inspect.stack()[1][0] | |
for name, mvar in self.metavars.items(): | |
frame.f_locals[name] = name | |
__all__= '_', |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment