[Tutor] Why are expressions not allowed as parameters in function definition statements?
Danny Yoo
dyoo at hashcollision.org
Sun Jun 19 00:20:21 EDT 2016
One other thing to add: the notion of pattern matching is often used
in mathematics. For example, if we want to define a function that
does something special to even numbers vs. odd numbers, it's not
uncommon to see the following when we want to describe a function `f`:
for `n` in the natural numbers:
f(2n) = <do something for the even numbers case>
f(2n+1) = <do something else for the odd numbers case>
where it's notationally convenient to express a function as a
collection of multiple cases, where we decide which case to use by
pattern matching against the argument to find the appropriate case to
use. We can contrast this style versus one which puts the case
analysis in the body of the function itself.
Again, it's just that we don't have direct support for this kind of
thing in Python.
On Sat, Jun 18, 2016 at 7:10 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Jun 18, 2016 at 02:04:46PM -0500, boB Stepp wrote:
>> I have (Finally!) gotten a bit of time to look at Peter's answer to my
>> Model-View-Controller question from May 29th, particularly his
>> CircleImageView class to which he added a "#FIXME" comment. I thought
>> it would be helpful to abbreviate his distance function in the
>> interpreter while I played around with pencil and graph paper. I got:
>>
>> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900
>> 64 bit (AMD64)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>> py3: def d(row, col/2, radius=5):
>> File "<stdin>", line 1
>> def d(row, col/2, radius=5):
>> ^
>> SyntaxError: invalid syntax
>>
>> And this surprised me.
>
> I'm surprised that you're surprised. I don't even know what you expect a
> parameter col/2 would even mean.
>
>> It seems that only identifiers are allowed as
>> parameters in a function definition statement, and I cannot help but
>> wonder why?
>
> Because they are parameters, which by definition are variable names,
> i.e. identifiers. What else could they be?
>
>
> def foo(x, 1+2, y):
> # how do I refer to the second parameter here?
>
> foo(1000, 2000, 3000) # what happens to the second argument here?
>
>
> Can you explain what you expected
>
> def d(row, col/2)
>
> to mean? I have literally no idea.
>
>> It seems that in most other places in Python's syntax it
>> will allow one to insert almost any kind of object or expression.
>
> You can't use arbitrary expressions on the left hand side of
> assignment:
>
> 1 + 2 = "some value"
> x/2 = y
>
> Function parameters are a form of assignment.
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list