创建对不同参数有效的命名元组

Creating namedtuple valid for differents parameters

我正在尝试找出一种方法来创建一个 namedtuple,其中包含可变字段,具体取决于您收到的数据,在我的例子中,我使用的数据来自StatCounter 而不是在所有时期都是相同的浏览器。我试过这种方法,但它有点难看,我相信有更好的方法来实现它。

def namedtuple_fixed(name: str, fields: List[str]) -> namedtuple:
    """Check the fields of the namedtuple and changes the invalid ones."""

    fields_fixed: List[str] = []

    for field in fields:
        field = field.replace(" ", "_")

        if field[0].isdigit():
            field = f"n{field}"

        fields_fixed.append(field)

    return namedtuple(name, fields_fixed)


Records: namedtuple = namedtuple("empty_namedtuple", "")


def read_file(file: str) -> List["Records"]:
    """
    Read the file with info about the percentage of use of various browsers
    """
    global Records

    with open(file, encoding="UTF-8") as browsers_file:
        reader: Iterator[List[str]] = csv.reader(browsers_file)
        field_names: List[str] = next(reader)
        Records = namedtuple_fixed("Record", field_names)
        result: List[Records] = [
            Records(
                *[
                    dt.datetime.strptime(n, "%Y-%m").date()
                    if record.index(n) == 0
                    else float(n)
                    for n in record
                ]
            )
            for record in reader
        ]
    return result

"namedtuple_fixed"功能是修复具有无效标识符的名称。

基本上,我想创建一个命名元组来接收可变数量的参数,具体取决于您要分析的文件。如果它结合了类型检查(我的意思是使用 typing 模块中的 NamedTuple),那就更好了。 提前致谢。

这解决了我的问题,但只是部分解决


class Record(SimpleNamespace):
    def __repr__(self):
        items = [f"{key}={value!r}" for key, value in self.__dict__.items()]
        return f"Record({', '.join(items)})"

使用 types.SimpleSpace 文档

它可能会导致问题,例如,如果您像下面这样初始化记录:

foo = Record(**{"a": 1, "3a": 2})
print(foo.a) # Ok
print(foo.3a) # Syntax Error