asmeurer / blog

My blog
https://www.asmeurer.com/blog/
8 stars 2 forks source link

Python Trickery | Aaron Meurer's Blog #6

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Python Trickery | Aaron Meurer's Blog

https://asmeurer.com/blog/posts/python-trickery/

asmeurer commented 3 years ago

To comment on this post, click on "Sign in with GitHub" below. If you don't want to authorize the Utterances bot, you can go to the GitHub issues page for this post and comment there.

asmeurer commented 3 years ago

These are the original comments on this post that were made when this blog used the Disqus blog system.

Comment from Marcus on 2015-05-21 15:27:11+00:00:

I like this post and your blog, only just found it today but I'll add it to my reading.
I think the first part is that "not" is not a function but actually an operator. It must have a lower precedence than the addition operator, so what you are actually asking python to do is
(1+not)(2)

If you write:
1+(not(2))
this works as you change the precedence.

The second one is much harder, I guess it arises from the rule that only named arguments may follow the unpacking of an argument list. A more concise example which generates an error would be
f(*[1],)
I can add named arguments,
f(*[1],x=1,y=2)
but if I add a comma it fails again:
f(*[1],x=1,y=2, )
Please let me know if I got this one right, I think I cracked the first.
Marcus

Replies:

Comment from asmeurer on 2015-05-21 15:47:32+00:00:

The first is right (the precedence of `not` isn't what is implied by the expression). The second is more subtle. See http://stackoverflow.com/q/....

Replies:

Comment from Marcus on 2015-05-24 21:58:17+00:00:

I'm disappointed that the language has this non-intuitive and inconsistent argument parsing behaviour, but thanks for highlighting it.

One thing I've noticed in the same vein as the first example is that, as python has no increment operators, expressions like this are perfectly valid:

1++-+-+--+5

As the unary operators have a high precedence we can also prefix this with a multiplication or divide
3*+-++-6

But you'd only do this to upset someone during a code review

Replies:

Comment from asmeurer on 2015-05-24 23:41:29+00:00:

Aside from being mathematically satisfying that that works, it's also useful because you can override unary + and - in your custom objects with __pos__ and __neg__.