Named tuple and default values for optional keyword arguments
Equip your NamedTuple with default values utilizing the collections
module and dataclasses
available from Python 3.7+. Here's an example:
This approach elegantly bundles default values with named tuple fields, boosting code clarity and expressiveness.
Dealing with defaults in lower Python versions
Setting internal defaults in ancient Python versions
If Python 3.7 still feels too futuristic and you're using earlier versions, setting defaults can feel a bit like a treasure hunt:
But worry not! For the Indiana Jones of coding using Python pre-3.6, replace the __defaults__
method with func_defaults
:
Overriding the old __new__
method
Distaste for traditional methods? Just subclass a NamedTuple
and override the __new__
to set your own default parameters:
Prototypes: a blueprint to success
Embrace your inner architect! Create a prototype instance and use the _replace
method for setting defaults:
Typing away with type annotations and defaults
Python 3.6.1+: a lifesaver for typing
Python 3.6.1+ improves our typing situation with typing.NamedTuple
, supporting type annotations and defaults in a cleaner and more elegant way:
Data classes: the new kids on the block
Data classes might be newcomers in Python 3.7, but they already rock as a solid alternative to namedtuples for complex structures:
Advanced maneuvers and avoiding pitfalls
Implementing slots: 'Don't touch my variables!'
If you're worried about dynamic creation of instance dictionaries (it wrecks havoc on memory!), implement __slots__
in a namedtuple subclass:
The future is now: Forward references
In Python 3.7+, forward references in type annotations work magic without quotation marks. All you need is a little help from a __future__
import:
Saving the day with wrapper functions
A wrapper function for setting defaults can handle both positional and mapping default values. Just like a superhero saving the day!
Was this article helpful?