Pythonic style
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Apr 28 01:31:55 EDT 2016
On Thursday 28 April 2016 13:23, Ben Finney wrote:
> Christopher Reimer <christopher_reimer at icloud.com> writes:
>
>> In short, my original code before I turned it into a separate
>> dictionary. *sigh*
>
> No, I think that misses the points that were being made. The discussion
> you're talking about was *not* to say “attribute access is better than
> dictionary access”, or vice versa. Each is good for its purpose.
>
> Rather, the discussion was to drive home the point that in Python those
> are *two distinct concepts*, and you need to not conflate them.
>
> If you want items in a mapping, explicitly use a Python ‘dict’ instance.
> If you want attributes that describe an object, explicitly use
> attributes of that object. Deliberately choose which one makes more
> sense.
Think of it like this: attribute access is for accessing parts of a thing:
dog.tail
car.engine
cup.handle
or one of a small number of fixed fields from a record:
employment_record.start_date
employee.salary
autopsy.cause_of_death
person.title
Mappings (dicts) are for recording a potentially unlimited number of
distinct records with arbitrary keys, especially since the keys don't have
to be valid identifiers:
employees['Fred Smith']
students['Joanna McTavish']
prisoners[12345]
catalog['Widgets']['GMH-12345']
dictionary['update']
While Python allows you to write code to use attribute syntax for item
access, doing so is a category mistake and leads to semantic confusion and
potential bugs:
employees.Fred_Smith
students.Joanna_McTavish
prisoners.P12345
parts.widgets.GMH_12345
dictionary.update
The last example shows how mixing up these two distinct concepts can lead to
problems. Should dictionary.update refer to the update method, or the entry
for the word "update"?
--
Steve
More information about the Python-list
mailing list