namedtupled icon indicating copy to clipboard operation
namedtupled copied to clipboard

Mixed tuples and dictionaries

Open clayrisser opened this issue 8 years ago • 4 comments

Is it possible to do mixed tuples and dictionaries???

There are times when I need to use special characters for the key, and tuples can't handle that.

clayrisser avatar Jun 27 '17 02:06 clayrisser

I think what you're after is possible with some exceptions: https://stackoverflow.com/questions/30503539/namedtuple-and-unicode-string

brennv avatar Jul 01 '17 08:07 brennv

I want to use a forward slash in a tuple

clayrisser avatar Jul 01 '17 08:07 clayrisser

This brings up a good point that's missing from the docs. We are currently limited to valid Python identifiers.

>>> import namedtupled as nt 
>>> nt.map({'/x':3})

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/../lib/python3.6/site-packages/namedtupled/namedtupled.py", line 11, in mapper
    return namedtuple_wrapper(_nt_name, **mapping)
  File "/../lib/python3.6/site-packages/namedtupled/namedtupled.py", line 18, in namedtuple_wrapper
    wrap = namedtuple(_nt_name, kwargs)
  File "/../lib/python3.6/collections/__init__.py", line 400, in namedtuple
    'identifiers: %r' % name)
ValueError: Type names and field names must be valid identifiers: '/x'

Another use case that would cause issues:

>>> nt.map({2: 'a'})

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/../lib/python3.6/site-packages/namedtupled/namedtupled.py", line 11, in mapper
    return namedtuple_wrapper(_nt_name, **mapping)
TypeError: namedtuple_wrapper() keywords must be strings

It might be helpful if we added a pre-flight check for valid Python identifiers:

>>> '/x'.isidentifier()
False
>>> '2'.isidentifier()
False
>>> 'meow.jpg'.isidentifier()
False

But in the end, using invalid Python identifiers would not be possible without some sort of character substitution schema. As an example:

{'example.com/pic-clicks': {'meow.jpg': 675}} 

Might be mapped to something like this, which is not ideal:

>>> example_dot_com_slash_pic-clicks.meow_dot_jpg
675

brennv avatar Jul 07 '17 15:07 brennv

Yeah, it should at least be mentioned in the docs. Adding some sort of mapping capabilities might not be a bad solution.

clayrisser avatar Jul 08 '17 02:07 clayrisser