Search code examples
linuxpython

ValueError: Type names and field names must be valid identifiers: 'Content-Type'


when I use

from allpairspy import AllPairs

parameters = OrderedDict([('Content-Type', ['"application/json"', ' "application/xml"'])]

test_cases = list(AllPairs(parameters))

it errors the following msg:

Traceback (most recent call last):
  File "/home/nio/Documents/projects/ironball/pairwise_engine/gen_pairwise_cases.py", line 60, in <module>
    for i, pairs in enumerate(AllPairs(parameters, filter_func=is_valid_combination)):
  File "/home/nio/miniconda3/envs/kytest/lib/python3.9/site-packages/allpairspy/allpairs.py", line 60, in __init__
    self.__pairs_class = namedtuple("Pairs", self.__param_name_list)
  File "/home/nio/miniconda3/envs/kytest/lib/python3.9/collections/__init__.py", line 390, in namedtuple
    raise ValueError('Type names and field names must be valid '
ValueError: Type names and field names must be valid identifiers: 'Content-Type'

when I changed 'Content-Type' into 'Content_Type', it works. But what is the problem here? How to use 'Content-Type' directly?


Solution

  • There is namedtuple under the hood and both typename and field_names of a namedtuple have to be "valid identifier".

    A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

    To check this condition isidentifier method is used:

    "Content-Type".isidentifier()  # False
    "Content_Type".isidentifier()  # True
    

    So, in your case it returns False and namedtuple raises and error.