Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #90147
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Subject | Re: Is this unpythonic? |
| Date | 2015-05-08 21:31 +1000 |
| References | <mihqhb$r1k$1@ger.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.235.1431084717.12865.python-list@python.org> (permalink) |
"Frank Millman" <frank@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Is this unpythonic? Ben Finney <ben+python@benfinney.id.au> - 2015-05-08 21:31 +1000
csiph-web