Search code examples
pythonstructpython-3.6mutablenamedtuple

Python mutable NamedTuple


I am looking for a struct like data structure I can create multiple instances from and have some type hinting without being immutable.

So I have something like this:

class ConnectionConfig(NamedTuple):
    name: str
    url: str
    port: int
    user: str = ""
    pwd: str = ""
    client: Any = None

But I would like to have it mutable. I could do it like that:

class ConnectionConfig():
    def __init__(self, name: str, url: str, port: int, user: str = "", pwd: str = "", client: Any = None):
        self.name = name
        self.url = url
        self.port = port
        self.user = user
        self.pwd = pwd
        self.client = client

But man... that is ugly :/ Are there any built-in alternatives in python? (using Python 3.6.3)


Solution

  • Your implementation is quite the (only) built-in way to do it, actually:

    class ConnectionConfig():
        def __init__(self, name: str, url: str, port: int, user: str = "",
                     pwd: str = "", client: Any = None):
            pass
    

    Reading PEP 0484 I haven't found any other alternatives that fit your needs. Continuing the PEP chain, I guess this quote from PEP 20 The Zen of Python explains it:

    There should be one-- and preferably only one --obvious way to do it.