Is this unpythonic?
Ben Finney
ben+python at benfinney.id.au
Fri May 8 07:31:44 EDT 2015
"Frank Millman" <frank at chagford.com> writes:
> If I use a list as an argument, I only use it to pass values *into*
> the function, but I never modify the list.
You've had good reasons why a mutable default argument is a good idea.
I'll address another aspect of the question: passing a structured
collection of values via a single parameter.
If those values *always* go together, it sounds like you have a class
which should be defined to make it explicit that they go together.
E.g., a contrived example::
def deliver_flowers(species, location=[0, 0, 0]):
""" Deliver the species of flower to the specified location. """
(x, y, z) = location
vehicle.load_with(species)
vehicle.drive_to(x, y, z)
vehicle.unload()
If the only reason you're using a collection is because those values
sensibly go together as a single named object, then define a class for
that::
class Point:
""" A three-dimensional point in space. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
centre = Point(0, 0, 0)
def deliver_flowers(species, location=centre):
""" Deliver the species of flower to the specified location. """
vehicle.load_with(species)
vehicle.drive_to(location.x, location.y, location.z)
vehicle.unload()
Too much overhead? If you want to collect a meaningful collection of
values together in the same way each time, but don't need any special
behaviour, then a class might be overkill.
Python has the ‘namedtuple’ type::
import collections
Point = collections.namedtuple('Point', ['x', 'y', 'z'])
centre = Point(0, 0, 0)
def deliver_flowers(species, location=centre):
""" Deliver the species of flower to the specified location. """
vehicle.load_with(species)
vehicle.drive_to(location.x, location.y, location.z)
vehicle.unload()
<URL:https://docs.python.org/3/library/collections.html#collections.namedtuple>
documents the surprisingly useful ‘namedtuple’ factory.
--
\ “It's a terrible paradox that most charities are driven by |
`\ religious belief.… if you think altruism without Jesus is not |
_o__) altruism, then you're a dick.” —Tim Minchin, 2010-11-28 |
Ben Finney
More information about the Python-list
mailing list