-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Kurt Rose
committed
Oct 23, 2019
1 parent
0e9c98f
commit 512bc31
Showing
4 changed files
with
63 additions
and
2 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
""" | ||
template mode is for building python literals, | ||
similar to quasi-quoting in lisp | ||
""" | ||
from glom import glom, MODE | ||
|
||
|
||
class Template(object): | ||
def __init__(self, spec): | ||
self.spec = spec | ||
|
||
def glomit(self, target, scope): | ||
scope[MODE] = _template | ||
return scope[glom](target, self.spec, scope) | ||
|
||
|
||
def _template(target, spec, scope): | ||
recurse = lambda val: scope[glom](target, val, scope) | ||
if type(spec) is dict: | ||
return {recurse(key): recurse(val) for key, val in spec.items()} | ||
if type(spec) in (list, tuple, set, frozenset): | ||
result = [recurse(val) for val in spec] | ||
if type(spec) is list: | ||
return result | ||
return type(spec)(result) | ||
if callable(spec): | ||
return spec(target) | ||
return spec |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
from glom import Template, T, glom | ||
|
||
def test(): | ||
assert glom('abc', Template((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'}) | ||
assert glom('123', Template({T[0], frozenset([T[1], T[2]])})) == {'1', frozenset(['2', '3'])} | ||
assert glom('xyz', Template([T[0], T[1], T[2]])) | ||
assert glom('abc', Template(lambda t: t.upper())) == 'ABC' |