[python-snuggs] 01/05: New upstream version 1.4.1

Johan Van de Wauw johanvdw-guest at moszumanska.debian.org
Sat Jan 7 19:33:24 UTC 2017


This is an automated email from the git hooks/post-receive script.

johanvdw-guest pushed a commit to branch master
in repository python-snuggs.

commit 177fa4c86d02075f96845aedffe385fc7ada336c
Author: Johan Van de Wauw <johan at vandewauw.be>
Date:   Sat Jan 7 18:53:54 2017 +0100

    New upstream version 1.4.1
---
 AUTHORS.txt         |  7 +++++++
 CHANGES.txt         |  5 +++++
 CODE_OF_CONDUCT.txt | 25 +++++++++++++++++++++++++
 README.rst          | 16 ++++++++++++++++
 snuggs/__init__.py  | 38 +++++++++++++++++---------------------
 test_snuggs.py      | 30 ++++++++++++++++++++++--------
 6 files changed, 92 insertions(+), 29 deletions(-)

diff --git a/AUTHORS.txt b/AUTHORS.txt
new file mode 100644
index 0000000..49c483c
--- /dev/null
+++ b/AUTHORS.txt
@@ -0,0 +1,7 @@
+Authors
+=======
+
+- Sean Gillies <sean at mapbox.com>
+- Chris Holden <ceholden at gmail.com>
+- Bas Couwenberg <sebastic at xs4all.nl>
+- Matthew Perry <perrygeo at gmail.com>
diff --git a/CHANGES.txt b/CHANGES.txt
index d962261..81fab18 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,11 @@
 Changes
 =======
 
+1.4.1 (2017-01-02)
+------------------
+- Bug fix: accept OrderedDict as evaluation context to enable reliable read()
+  indexing (#9, #10).
+
 1.4.0 (2016-07-12)
 ------------------
 - New feature: mathematical operators like + and * can take multiple arguments
diff --git a/CODE_OF_CONDUCT.txt b/CODE_OF_CONDUCT.txt
new file mode 100644
index 0000000..ad8236f
--- /dev/null
+++ b/CODE_OF_CONDUCT.txt
@@ -0,0 +1,25 @@
+Contributor Code of Conduct
+---------------------------
+
+As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
+
+We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery
+* Personal attacks
+* Trolling or insulting/derogatory comments
+* Public or private harassment
+* Publishing other's private information, such as physical or electronic addresses, without explicit permission
+* Other unethical or unprofessional conduct.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
+
+This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
+
+This Code of Conduct is adapted from the `Contributor Covenant`_, version 1.2.0, available at http://contributor-covenant.org/version/1/2/0/
+
+.. _Contributor Covenant: http://contributor-covenant.org
diff --git a/README.rst b/README.rst
index 67e8ade..7ec1b5c 100644
--- a/README.rst
+++ b/README.rst
@@ -57,6 +57,22 @@ Expressions can also refer by name to arrays in a local context.
     snuggs.eval("(+ (asarray 1 1) b)", b=np.array([2, 2]))
     # array([3, 3])
 
+This local context may be provided using keyword arguments (e.g.,
+``b=np.array([2, 2])``), or by passing a dictionary that stores
+the keys and associated array values. Passing a dictionary, specifically
+an ``OrderedDict``, is important when using a function or operator that
+references the order in which values have been provided. For example,
+the ``read`` function will lookup the `i-th` value passed:
+
+.. code-block:: python
+
+    ctx = OrderedDict((
+        ('a', np.array([5, 5])),
+        ('b', np.array([2, 2]))
+    ))
+    snuggs.eval("(- (read 1) (read 2))", ctx)
+    # array([3, 3])
+
 Functions and operators
 =======================
 
diff --git a/snuggs/__init__.py b/snuggs/__init__.py
index 86ff1aa..73fd0e7 100644
--- a/snuggs/__init__.py
+++ b/snuggs/__init__.py
@@ -1,7 +1,7 @@
 """
 Snuggs are s-expressions for Numpy.
 """
-
+from collections import OrderedDict
 import functools
 import itertools
 import operator
@@ -11,13 +11,13 @@ import sys
 from pyparsing import (
     alphanums, ZeroOrMore, nums, oneOf, Word, Literal, Combine, QuotedString,
     ParseException, Forward, Group, CaselessLiteral, Optional, alphas,
-    OneOrMore, ParseResults, ParseException)
+    OneOrMore, ParseResults)
 
 import numpy
 
 
 __all__ = ['eval']
-__version__ = "1.4.0"
+__version__ = "1.4.1"
 
 # Python 2-3 compatibility
 string_types = (str,) if sys.version_info[0] >= 3 else (basestring,)
@@ -26,7 +26,7 @@ string_types = (str,) if sys.version_info[0] >= 3 else (basestring,)
 class Context(object):
 
     def __init__(self):
-        self._data = {}
+        self._data = OrderedDict()
 
     def add(self, name, val):
         self._data[name] = val
@@ -35,22 +35,22 @@ class Context(object):
         return self._data[name]
 
     def lookup(self, index, subindex=None):
-        s = list(self._data.values())[int(index)-1]
+        s = list(self._data.values())[int(index) - 1]
         if subindex:
-            return s[int(subindex)-1]
+            return s[int(subindex) - 1]
         else:
             return s
 
     def clear(self):
-        self._data = {}
+        self._data = OrderedDict()
 
 _ctx = Context()
 
 
 class ctx(object):
 
-    def __init__(self, **kwds):
-        self.kwds = kwds
+    def __init__(self, kwd_dict=None, **kwds):
+        self.kwds = kwd_dict or kwds
 
     def __enter__(self):
         _ctx.clear()
@@ -80,8 +80,7 @@ op_map = {
     '==': operator.eq,
     '!=': operator.ne,
     '>=': operator.ge,
-    '>': operator.gt,
-    }
+    '>': operator.gt}
 
 def asarray(*args):
     if len(args) == 1 and hasattr(args[0], '__iter__'):
@@ -92,13 +91,11 @@ def asarray(*args):
 func_map = {
     'asarray': asarray,
     'read': _ctx.lookup,
-    'take': lambda a, idx: numpy.take(a, idx-1, axis=0),
-    }
+    'take': lambda a, idx: numpy.take(a, idx - 1, axis=0)}
 
 higher_func_map = {
     'map': map if sys.version_info[0] >= 3 else itertools.imap,
-    'partial': functools.partial,
-    }
+    'partial': functools.partial}
 
 # Definition of the grammar.
 decimal = Literal('.')
@@ -122,14 +119,12 @@ var = name.setParseAction(resolve_var)
 
 integer = Combine(
     Optional(sign) +
-    number
-    ).setParseAction(lambda s, l, t: int(t[0]))
+    number).setParseAction(lambda s, l, t: int(t[0]))
 
 real = Combine(
     integer +
     decimal + Optional(number) +
-    Optional(e + integer)
-    ).setParseAction(lambda s, l, t: float(t[0]))
+    Optional(e + integer)).setParseAction(lambda s, l, t: float(t[0]))
 
 string = QuotedString("'") | QuotedString('"')
 
@@ -205,6 +200,7 @@ def handleLine(line):
         raise err
 
 
-def eval(source, **kwds):
-    with ctx(**kwds):
+def eval(source, kwd_dict=None, **kwds):
+    kwd_dict = kwd_dict or kwds
+    with ctx(kwd_dict):
         return handleLine(source)
diff --git a/test_snuggs.py b/test_snuggs.py
index bb148fa..117be20 100644
--- a/test_snuggs.py
+++ b/test_snuggs.py
@@ -1,3 +1,5 @@
+from collections import OrderedDict
+
 import numpy
 import pytest
 
@@ -40,7 +42,19 @@ def test_arr_var(ones):
 
 
 def test_arr_lookup(ones):
-    r = snuggs.eval('(read 1)', foo=ones)
+    kwargs = OrderedDict((('foo', ones),
+                          ('bar', 2.0 * ones),
+                          ('a', 3.0 * ones)))
+    r = snuggs.eval('(read 1)', kwargs)
+    assert list(r.flatten()) == [1, 1, 1, 1]
+
+
+ at pytest.mark.xfail(reason="Keyword argument order can't be relied on")
+def test_arr_lookup_kwarg_order(ones):
+    kwargs = OrderedDict((('foo', ones),
+                          ('bar', 2.0 * ones),
+                          ('a', 3.0 * ones)))
+    r = snuggs.eval('(read 1)', **kwargs)
     assert list(r.flatten()) == [1, 1, 1, 1]
 
 
@@ -158,7 +172,7 @@ def test_masked_arr():
 # Parse and syntax error testing.
 def test_missing_closing_paren():
     with pytest.raises(SyntaxError) as excinfo:
-        result = snuggs.eval("(+ 1 2")
+        snuggs.eval("(+ 1 2")
     assert excinfo.value.lineno == 1
     assert excinfo.value.offset == 7
     exception_options = ['expected a function or operator',
@@ -168,7 +182,7 @@ def test_missing_closing_paren():
 
 def test_missing_func():
     with pytest.raises(SyntaxError) as excinfo:
-        result = snuggs.eval("(0 1 2)")
+        snuggs.eval("(0 1 2)")
     assert excinfo.value.lineno == 1
     assert excinfo.value.offset == 2
     assert str(excinfo.value) == "'0' is not a function or operator"
@@ -176,7 +190,7 @@ def test_missing_func():
 
 def test_missing_func2():
     with pytest.raises(SyntaxError) as excinfo:
-        result = snuggs.eval("(# 1 2)")
+        snuggs.eval("(# 1 2)")
     assert excinfo.value.lineno == 1
     assert excinfo.value.offset == 2
     exception_options = ['expected a function or operator',
@@ -186,7 +200,7 @@ def test_missing_func2():
 
 def test_undefined_var():
     with pytest.raises(SyntaxError) as excinfo:
-        result = snuggs.eval("(+ 1 bogus)")
+        snuggs.eval("(+ 1 bogus)")
     assert excinfo.value.lineno == 1
     assert excinfo.value.offset == 6
     assert str(excinfo.value) == "name 'bogus' is not defined"
@@ -194,7 +208,7 @@ def test_undefined_var():
 
 def test_bogus_higher_order_func():
     with pytest.raises(SyntaxError) as excinfo:
-        result = snuggs.eval("((bogus * 2) 2)")
+        snuggs.eval("((bogus * 2) 2)")
     assert excinfo.value.lineno == 1
     assert excinfo.value.offset == 3
     exception_options = ['expected a function or operator',
@@ -203,8 +217,8 @@ def test_bogus_higher_order_func():
 
 
 def test_type_error():
-    with pytest.raises(TypeError) as excinfo:
-        result = snuggs.eval("(+ 1 'bogus')")
+    with pytest.raises(TypeError):
+        snuggs.eval("(+ 1 'bogus')")
 
 
 # Fixtures.

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/python-snuggs.git



More information about the Pkg-grass-devel mailing list