2

I have this data type that just groups related data. It should be a struct-like thing, so I opted for a namedtuple.

ConfigOption = namedtuple('ConfigOption', 'one two animal vehicle fairytale')

On the other hand, namedtuple has no defaults, so I reside to a hack proposed in another answer.

ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella")

Obviously, this makes the type check fail: error: "Callable[[Type[NT], Any, Any, Any, Any, Any], NT]" has no attribute "__defaults__"

Since I'm well aware this is a hack, I tell the type checker so using an inline comment # type: disable:

ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella")  # type: disable

At this time... the line becomes too long. I have no idea how to break this line so that it is syntactically correct and at the same time make the type checker skip it:

# the ignore is on the wrong line
ConfigOption.__new__.__defaults__ = \
    (1, 2, "White Horse", "Pumpkin", "Cinderella")  # type: ignore

# unexpected indentation
ConfigOption.__new__.__defaults__ =  # type: ignore
    (1, 2, "White Horse", "Pumpkin", "Cinderella")

So is there a way to exclude a single line from type checking, or to format this long line, so that both the type check is skipped, and the line length is pep-8 compliant?

xtofl
  • 40,723
  • 12
  • 105
  • 192

2 Answers2

2

what's wrong with:

option_defaults = (1, 2, "White Horse", "Pumpkin", "Cinderella")
ConfigOption.__new__.__defaults__ = option_defaults  # type: ignore
Sebastian Loehner
  • 1,302
  • 7
  • 5
0

Enum seems to follow the constraints you require, and is quite concise.

You can use the Functional API, which itself says the semantics resemble namedtuple

>>> from enum import Enum
>>> Enum('ConfigOption', 'one two animal vehicle fairytale')
<enum 'ConfigOption'>
>>> ConfigOption = Enum('ConfigOption', 'one two animal vehicle fairytale')
>>> [c for c in ConfigOption]
[<ConfigOption.one: 1>, <ConfigOption.two: 2>, <ConfigOption.animal: 3>, <ConfigOption.vehicle: 4>, <ConfigOption.fairytale: 5>]
Nathan McCoy
  • 3,092
  • 1
  • 24
  • 46