by sfvisser · 5y ago · 0 comments
I must come from a different world. What is going on here?
Are you dynamically creating a named tuple (a record?) by passing a space separated list of field names? Why?
As for the unusual space-delimited syntax, the missing context here is that namedtuple is a very, very old part of Python that predates the conventions now considered good style. Using space delimiters for lists of strings is a common idiom in Perl scripting due to the `qw()` quote syntax. Note the archetypical context where namedtuple was imagined to apply (record-oriented processing of logs and SQL result sets) was commonly handled using Perl before Python became dominant.
Namedtuple is definitely the most prominent example of this syntax convention in Python, but other libraries use it too. `enum.Enum` supports a function-like interface directly modeled off namedtuple. It’s a mildly bad idea to keep using it IMHO because it complicates static analysis or refactoring. If someone does a wide search-and-replace of a field name literal it’s easy to miss this edge case.
Note that the Smalltalk-80 class creation method also expects a space-separated string of instance variable names, and that's an environment considerably older than Perl.
Point = namedtuple('Point', ['x', 'y'])> The field_names are a sequence of strings such as ['x', 'y']. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'.
You could imagine the function dynamically creates the class by manipulating the underlying dictionary (or whatever the "slot" alternative uses). At that level of python, attributes are strings anyway. Handling spaces is just a matter of calling .split().
In modern python, there's a whole metaclass system that would possibly let you do the equivalent without getting your hands dirty with internal data structures.
There's definitely a class of persnickety coders out there though. As a technical leader within a growing organization, sometimes the bulk of my time spent in a code review turns into style guide enforcement. It can get old arguing about the subtle merits of someone's preferred but style violating syntax over and over, especially when all I care about is maintaining a standard of consistency.
Point = namedtuple('Point', ('x', 'y'))
Support for a space and/or comma separated strings was requested by users. It made life easier for them when syncing with other space/comma separated strings. For example, an SQL query, "SELECT name, rank, serial_number FROM Soldiers;" would have a corresponding named tuple where the field names could be cut-and-pasted from the SQL query. Soldier = namedtuple('Soldier', 'name, rank, serial_number')I wish more library devs would go out of their way to add such niceties.
A big one that I always do is if I'm expecting an iterator of objects I make it just work with one.
from collections.abc import Iterable
def my_function(arg):
# slightly different if you're looking for a collection of strings or bytes
if not isinstance(arg, Iterable):
arg = [arg]
for item in arg:
do the thing
Or if you have a specific type of object you want it goes like this from collections.abc import Iterable
def my_function(arg):
if isinstance(arg, MyObjectIWant):
arg = [arg]
for item in arg:
do the thing
I like to think of my libraries as mini programs for users, and I hate when validation is too strict, when it could be so easy to fix. Like when a phone number validator insists on (XXX)XXX-XXXX or XXX.XXX.XXXX or XXXXXXXXXX when it could just ignore everything that isn't a number and make sure there is 10 of them.A great case study in the issues here is Pandas, which routinely allows arguments to be columns, lists of columns, string column labels, lists of string column labels, and so on. It works surprisingly well, but at the cost of inventing a new semantic distinction between `list` objects and other sequence types like `tuple` — someone unfamiliar with Pandas who thinks “Why does this need to be a list comprehension when a generator expression will do?” is likely introducing a bug.
Another subtle issue is that code permissive with inputs is harder to extend via wrapper code. Suppose you have a function that does some sort of processing for any number of given datetimes, but also accepts integer seconds since 1970-01-01, a formatted date string, or any mixed sequence of these types. If you need to write a wrapper that first rounds all times to the most recent hour, your task is much easier if the only accepted type is `Iterable[datetime]`.
Saves a bunch of typing. 5 chars:
'x y'
vs 10: ['x', 'y']For a suitable definition of “non-trivial” and “readable” (where the former is “long list of attributes” and the latter is “long attribute names”), I’d agree, but plenty of real, serious namedtuple use is for namedtuples with small numbers of short attribute names, and those are more readable (in the literal sense) this way.
OTOH, for the nontrivial, static uses, you probably want to skip right past namedtuple() with a static list of string literals for names to typing.NamedTuple with its dataclass-like syntax, including type hints, since its more readable and also supports typing.
> Also, the amount of time saved typing is miniscule in comparison to all the rest of the development work that'll happen.
Sure, but if you start passing on providing (or, on the other side, using) conveniences because each is small in isolation, the aggregate cost ends up being high.
No, it's creating a namedtuple type, aka a subclass of `tuple`. So the fieldnames are literally the names given to the tuple's items: Point is a pair (a two-uple) whose 0th item can be accessed as `x` and 1st item `y`.
Very little in python is bound statically. This is akin to a type definition. The type will behave as an ordered tuple that can be indexed but also alias these attribute names to those ordinals.
assert(a == Point(a, b).x)
assert(b == Point(a, b).y)
assert(a == Point(a, b)[0])I believe that's called "procedural record interface" in Scheme and it does have its uses, for example if you need to create records for data the structure of which you don't know in advance.