NamedTuple declaration and use in a single line
There is no need for the temporary name Dimension
:
dim = namedtuple('Dimension', ['x', 'y'])(2, 3)
Alternatively, you can use the three-argument form of type
to create a new class and create an instance of it:
dim = type('Dimension', (object,), {'x': 2, 'y': 3})()
This object will use more memory but, unlike the namedtuple
, will be mutable (this may or may not be a good thing for your use cases). It also saves an import
.
I've come across this issue myself a lot; what would be great is if the Python standard library had the following convenience function built in to the collections
module. But in lieu of that, you can always define this yourself locally:
def make_namedtuple(class_name, **fields):
return namedtuple(class_name, fields)(*fields.values())
With this you could instantiate a new, single-use namedtuple class for a single instance like so:
dim = make_namedtuple('Dimension', x=2, y=3)
This works for Python 3.6+[1].
[1] the **fields
' order is not maintained on Python versions <3.6 (in other words, pre-PEP 468). You can still use the function, but it kind of defeats the purpose of having a class that unpacks like a tuple, imo...