[Tutor] Why are expressions not allowed as parameters in function definition statements?
Steven D'Aprano
steve at pearwood.info
Sun Jun 19 04:47:31 EDT 2016
On Sat, Jun 18, 2016 at 09:04:10PM -0700, Danny Yoo wrote:
> > You know Steve, as I was typing the beginning of a reply responding to
> > a similar question you asked earlier in your response, I suddenly
> > realized how ridiculous having a parameter of 'col/2' is! I'll just
> > have either eat crow or attribute this to a brain fart. You pick!
>
> Just to play devil's advocate: it's not crazy. Essentially, what
> you're asking for is called "pattern matching", and it is done in a
> class of many programming languages.
Ah, I didn't think of pattern matching. Another good example is Haskell.
But still, even with pattern matching, I'm not sure that col/2 would be
a useful pattern. That would match any number.
[...]
> It's a bit out of scope to talk about this much here, but I just
> wanted to chime in here to say that you are not ridiculous. :P But
> Python does not have a robust pattern matching facility; the closest
> it has is a limited form of tuple matching:
>
> ######################
> > def f((x,y), z):
> ... print x, y, z
> ...
> > f([1, 2], 3)
> 1 2 3
> ######################
That's not so much *matching tuples* as expanding any iterable object.
It is equivalent to:
def f(_tmp, z):
x, y = _tmp
del _tmp
print x, y, z
> with very limited applicability and rarely used.
In Python 2, it's unusual. In Python 3, it's impossible, as the facility
is removed from the language.
--
Steve
More information about the Tutor
mailing list