Live data from Hacker News

Advanced Python Features

blog.edward-li.com

81–90 of 183 posts

Re: Advanced Python Features

#81

Some of these newer features don't seem like improvements to the language (e.g. the Walrus operator): ''' # ===== Don't write this ===== response = get_user_input() if response: print('You pressed:', response) else: print('You pressed nothing') # ===== Write this instead ===== if response := get_user_input(): print('You pressed:', response) else: print('You pressed nothing') ''' The first implementation is immediatel…

In that example I gave, I totally agree with you. One area where I find walrus operators kinda useful is with dealing with iterators. For example,

'''

iterable = iter(thing)

while val := next(iterable, None): print(val)

'''

is a lot cleaner in my opinion compared to

'''

iterable = iter(thing)

val = next(iterable, None) while val is not None: print(val) val = next(iterable, None)

'''

Reason why I did not use this example outright was because I wasn't sure if people were familiar with the iter api, so I just chose a simpler example for the blog.

Re: Advanced Python Features

#82
post #60
post #54

Earlier quoted context omitted.

It's more complex that decade ago, but still a relatively simple language. I can understand the article without much effort, while I scratch my head really hard when read about advance feature of Typescript or Scala.

> still a relatively simple language If only. I suspect very few Python programmers can even fully explain what `a + b` does. If `a` and `b` are instances of classes, many would say it's equivalent to `a.__add__(b)` or `type(a).__add__(a, b)`, but in fact it's much more complex.

I once broke some Python by changing a = a + b to a += b.

If a and b are lists, the latter modifies the existing list (which may be referenced elsewhere) instead of creating a new one.

I think Python is the only language I've encountered that uses the + operator with mutable reference semantics like this. It seems like a poor design choice.

Re: Advanced Python Features

#83

Some of these newer features don't seem like improvements to the language (e.g. the Walrus operator): ''' # ===== Don't write this ===== response = get_user_input() if response: print('You pressed:', response) else: print('You pressed nothing') # ===== Write this instead ===== if response := get_user_input(): print('You pressed:', response) else: print('You pressed nothing') ''' The first implementation is immediatel…

I disagree.

First of all, it takes a minute to search "python :=", and the construct itself is pretty simple. It's been part of the language since 2018[0]. I don't think "not knowing the language" is a good reason to avoid it.

Second, the walrus operator limits the variable's scope to the conditional, which can reduce certain bugs. It also makes some scenarios (like if/elif chains) clearer.

I recommend checking out the PEP for some real-world examples.

[0] https://peps.python.org/pep-0572/

Edit: my point about walrus scoping is incorrect. The new variable is function-scoped.

Re: Advanced Python Features

#84

Some of these newer features don't seem like improvements to the language (e.g. the Walrus operator): ''' # ===== Don't write this ===== response = get_user_input() if response: print('You pressed:', response) else: print('You pressed nothing') # ===== Write this instead ===== if response := get_user_input(): print('You pressed:', response) else: print('You pressed nothing') ''' The first implementation is immediatel…

Couldn't you extend this line of thinking to any language-specific syntax on any programming language?

Don't use `match`, macros, lifetimes, ... in rust, someone coming from another language without them might not get what it means. Instead write the equivalent C-looking code and don't take advantage of any rust specific things.

Don't use lisp, someone coming from another language might not be able to read it.

Etc..

At one point if you write code and want to be productive, you need to accept that maybe someone that is not familiar with the language you're using _might_ have to look up syntax to understand what's going on.

Re: Advanced Python Features

#85

Some of these newer features don't seem like improvements to the language (e.g. the Walrus operator): ''' # ===== Don't write this ===== response = get_user_input() if response: print('You pressed:', response) else: print('You pressed nothing') # ===== Write this instead ===== if response := get_user_input(): print('You pressed:', response) else: print('You pressed nothing') ''' The first implementation is immediatel…

In that example I gave, I totally agree with you. One area where I find walrus operators kinda useful is with dealing with iterators. For example, ''' iterable = iter(thing) while val := next(iterable, None): print(val) ''' is a lot cleaner in my opinion compared to ''' iterable = iter(thing) val = next(iterable, None) while val is not None: print(val) val = next(iterable, None) ''' Reason why I did not use this exam…

Isn't this equivalent to just `for val in thing`?

Re: Advanced Python Features

#86
Good article! I found the typing bits particularly interesting. This part of the language has been evolving rapidly recently, which is cool if you like static typing.

Although I think the example of type alises in section 4 is not quite right. NewType creates a new "subtype" which is not equivalent to the original type. That's different to TypeAlias, which simply assigns a name to an existing type. Hence NewType is still useful in Python 3.12+.

Re: Advanced Python Features

#87
post #27

Earlier quoted context omitted.

Try: def f(i=0) -> None: reveal_type(i) The inferred type is not `float` nor `int`, but `Any`. Mypy will happily let you call `f("some string")`.

So you want strong typing, but then are to lazy to properly type your function definitions?

no need to explicitly write the type if you have type inference:

  > # fun x -> x + 1;;
  > - : int -> int = 
  >

Re: Advanced Python Features

#88
post #9

I would argue that most of these features (basically everything except metaclasses) are not advanced features. These are simple, but for some reason less well known or less used features. Metaclasses are however quite complex (or at least lead to complex behavior) and I mostly avoid them for this reason. And 'Proxy Properties' are not really a feature at all. Just a specific usage of dunder methods.

Simple doesn’t make something basic or beginner level.

Re: Advanced Python Features

#89
post #61

Every time I try to use Python I get this mixed feeling of liking how few guard rails there are between me and the logic I am making and this lingering worry that my code looks like fools attempt to use Python. So much exists as convention or loosely followed rules. Whenever I read articles like this I am wowed by the depth of things I didn't know about Python or how much has changed. It makes something like Go feel…

There are plenty of language features which let you re-use or build your own guardrails in python. I do with the concept of truthiness and falsiness would be taken out and shot though. It's been responsible for far too many nasty bugs IME and it only cuts out a few extra characters. Not a great trade off.

Truthiness and falsiness is one of my more used features. ``if not collection`` comes up in nearly every project multiple times.

Re: Advanced Python Features

#90

I enjoyed reading the article. I'm far from a Python expert, but as an observation, most of these features are actually just typing module features. In particular, I wasn't sold on Generics or Protocols as I would have just used duck typing in both cases... Does modern, production-level python code use types everywhere? Is duck typing frowned upon?

> Does modern, production-level python code use types everywhere?

I don't know about code inside companies, but most new open source projects I encounter use typing. Many old ones have been converted too.

> Is duck typing frowned upon?

No. You can use Protocols to define what shape you expect your duck to be. There's some discussion about whether you should use abstract classes or protocols, though.

Post reply on HN