Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 574
Jodo Avatar asked Oct 18 '25 15:10

Jodo


1 Answers

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.

like image 171
viddik13 Avatar answered Oct 20 '25 06:10

viddik13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!