fluentpython / example-code-2e

Example code for Fluent Python, 2nd edition (O'Reilly 2022)
https://amzn.to/3J48u2J
MIT License
3.17k stars 902 forks source link

Modernize code to Python 3.6+ and some cleanup #3

Closed eumiro closed 3 years ago

eumiro commented 3 years ago

Hi Luciano, I have some random cleanups for your repository. Sorry for the single commit. Please ask for any details/reasons in my PR.

Generally, most updates can be grouped in following categories:

Looking forward to your feedback!

ramalho commented 3 years ago

Thank you so much, @eumiro !

ramalho commented 3 years ago

In a few places where I used math.floor, I had an expression like math.floor(math.sqrt(n)).

It turns out Python 3.8 added a math.isqrt function that does what I needed, so that's even more modern!

I would not have found it if you didn't make me look at that code again. Thanks!

eumiro commented 3 years ago

That's a very good point. It depends on where you officially “pin” your book. When I write a new project where I control the whole environment, then I'd go with Python 3.9 (and use that math.isqrt happily). On the other hand, if I write a library and want to offer modern code to my users, I'd go currently (February 2021) with Python 3.6–3.9 and therefore without math.isqrt.

That's exactly the reason why this PR aimed for Python 3.6+. Next year I'd aim for 3.7+ and start using dataclasses.

ramalho commented 3 years ago

For the book, I aim for the latest official release—that was also my policy in the first edition.

The upsides are showing the readers new features they may not know about, and making the book as fresh as possible, given that updates are difficult in the traditional editorial process of book publishing.

The downside is minimal: the programs are all very short, so fixing for incompatibilities of that kind is easy. The top reason I see for readers to use 3.7 at the moment is to run the examples with Pypy.

BTW, as soon as Mypy 0.800 started accepting generic built-ins (like list[int]) I started removing all redundant imports like from typing import List, Tuple, Dict etc. I added a note about that matter in the first occurrence (in Chapter 5) and that's it. I think that's a good usability improvement for typing. There was already a whole section about that issue in Chapter 8. The difference is that now I assume Python 3.9 and Mypy 0.800 in the code examples that use generics.