« Back to Index

[Python Named Tuples Default Values]

View original Gist on GitHub

Tags: #python #defaults #namedtuple

Example Usage.py

def client_adapter(client):
    """Mimic interface for a specific concrete client implementation.
    
    The requirement for the 'fetcher' is that there needs to be 'post' and 'get' methods.
    """

    a = namedtuple('_', ['get', 'post'])
    a.__new__.__defaults__ = (client.fetch, ) * len(a._fields)
    return a()

  
AsyncHTTPClient.configure(None, defaults=dict(user_agent="MyCustomAgent"))

fetcher = configure_fetch(client_adapter(AsyncHTTPClient()))

# fetcher.get(...)
# fetcher.post(...)

Python Named Tuples Default Values.py

# Pre-Python 3.7.1

x = namedtuple('_', ['get', 'post'])
x.__new__.__defaults__ = (1, ) * len(x._fields)

y = x()
y.get
1
y.post
1

# Python 3.7.1+

fields = ('get', 'post')
x = namedtuple('_', fields, defaults=(1, ) * len(('get', 'post')))

y = x()
y.get
1
y.post
1