Commits

Andriy Kornatskyy committed a02fe74

Improved key_builder with ability to build key functions out from arguments that defaults to objects (not just simple types).

Comments (0)

Files changed (2)

src/wheezy/caching/patterns.py

         argnames, varargs, kwargs, defaults = getargspec(func)
         if defaults:
             n = len(defaults)
+            defaults = dict(zip(argnames[-n:], defaults))
             args = argnames[:-n]
-            args.extend('%s=%r' % x for x in zip(argnames[-n:], defaults))
+            args.extend('%s=defaults["%s"]' % (n, n) for n in argnames[-n:])
         else:
             args = argnames
         if argnames and argnames[0] in ('self', 'cls', 'klass'):
             argnames = argnames[1:]
         fname = 'key_' + func.__name__
-        code = 'def %s(%s): return "%s" %% (%s)' % (
+        code = 'def %s(%s): return "%s" %% (%s)\ndel defaults' % (
             fname, ', '.join(args), key_format(func, key_prefix),
             ', '.join(argnames))
-        return compile_source(code, 'keys_' + key_prefix)[fname]
+        return compile_source(code, 'keys_' + key_prefix, defaults)[fname]
     return build
 
 
 # region: internal details
 
-def compile_source(source, name):
+def compile_source(source, name, defaults):
     compiled = compile(source, name, 'exec')
-    local_vars = {}
+    local_vars = {'defaults': defaults}
     exec(compiled, {}, local_vars)
     return local_vars

src/wheezy/caching/tests/test_patterns.py

         assert 'prefix-items:1' == self.mk(items)('cls', 1)
         assert 'prefix-items:None' == self.mk(items)('cls', None)
         assert "prefix-items:''" == self.mk(items)('cls', '')
+
+    def test_object(self):
+        class Spec(object):
+            def __init__(self, locale='en'):
+                self.locale = locale
+
+            def __repr__(self):
+                return '<spec:%s>' % self.locale
+
+        def items(spec):
+            pass
+        assert 'prefix-items:<spec:en>' == self.mk(items)(Spec())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.