Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

handle reserved words used as dictionary keys #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions namedtupled/namedtupled.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import keyword
import builtins
from future import standard_library
standard_library.install_aliases()
from collections import Mapping, namedtuple, UserDict

RESERVED = keyword.kwlist + dir(builtins)

def mapper(mapping, _nt_name='NT'):
""" Convert mappings to namedtuples recursively. """
Expand All @@ -15,6 +18,15 @@ def mapper(mapping, _nt_name='NT'):


def namedtuple_wrapper(_nt_name, **kwargs):
for k in kwargs:
if k in RESERVED:
new_k = k + '_'
val = kwargs.pop(k)
if new_k in kwargs:
msg = "Can't rename the field {} to {}. {} already exist"
raise ValueError(msg.format(k, new_k, new_k))
kwargs.update({new_k: val})

wrap = namedtuple(_nt_name, kwargs)
return wrap(**kwargs)

Expand Down
28 changes: 28 additions & 0 deletions tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@

mapping_array = [mapping, mapping]

mapping_keywords = {
'baz': 'bar',
'from': 'John Doe'
}

mapping_keywords_dup = {
'baz': 'bar',
'from': 'John Doe',
'from_': 'Acme Corp'
}


def test_namedtupled_map_object(mapping=mapping):
t = namedtupled.map(mapping)
Expand All @@ -43,3 +54,20 @@ def test_namedtupled_map_array(mapping=mapping_array):
assert t[0].alist[1].two == '2'
assert t[0].baz != {'qux': 'quux'}
assert t[0].alist[0] != {'one': '1', 'a': 'A'}


def test_namedtupled_map_object_keywords(mapping=mapping_keywords):
try:
t = namedtupled.map(mapping)
except ValueError:
# Type names and field names cannot be a keyword: 'from'
assert False

assert t.from_ == 'John Doe'
assert len(t._fields) == len(mapping)

def test_namedtupled_map_object_keywords_dup(mapping=mapping_keywords_dup):
try:
t = namedtupled.map(mapping)
except ValueError:
assert True