r/learnpython • u/NovaRunner • Jan 22 '22
Today I discovered f strings and it made my day
I first learned the basics of Python about 10 years ago and really haven't done much with it since. Recently I picked it back up but instead of good old 2.7 I'm using 3.10 and today I found out about f strings. Man, what a revelation--something so simple yet so useful.
Since posts must contain a question about Python, what other nifty new things will I find in 3.10?
ETA: Wow, thanks everyone! What a wealth of information. I appreciate everyone's input.
125
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 22 '22 edited Jan 22 '22
F-strings were added in 3.6, so you're probably missing a lot of information. I'll highlight some, but listing all changes is best left for the official changelogs.
pathlibis a new cross-platform object-oriented filepath module in the standard library, combining the functionality ofos.pathandglobwith much less boilerplate. I highly recommend getting used to it especially if you occasionally deal with the filesystem. All built-in functionality that expects a filepath also accepts these objects, so no need to convert to string. In a nutshell they implement theos.PathLikeinterface.Dictionaries are now sorted in insertion order. This begun as an optimisation of CPython, but later on was made part of the language standard.
Type hints (or annotations) are getting widespread use. Especially in function parameters and return types, but they work elsewhere too.
def add(first: int, second: int) -> int: return first + secondThe interpreter ignores them, it's not an optimisation trick, but many IDEs can help you prevent type-related problems if you use them. They can show you a warning if you're giving a string to a parameter expecting a numeric type, for instance.
EDIT: The new
typingmodule is relevant, too, as it includes "generic" types likeGeneratororUnion(== any type within). Also contains generics for lists (List) and other built-in collections, but since 3.10 the built-in variants can be used as generics for type hints as well so they're only used in code run on older versions now.from typing import Generator def fib_gen() -> Generator[int, None, None]: a, b = 0, 1 while True: yield a a, b = b, a+bThe new
breakpointfunction is very handy for debugging code. It halts the execution when encountered, and opens the current state in the Python debugger, allowing you to do things like execute line by line or check current values.Data classes are now a thing, they make creating new classes much more straightforward by giving you most methods "for free", like comparison operators or
__init__.
I'm sure there are many more, but that's off the top of my head right now.
EDIT: Added info on the typing module.
28
u/stoveisastove Jan 22 '22
pathlib is the work of Gods. It’s so fucking intuitive
13
u/johnnymo1 Jan 22 '22
The use of the / operator is just beautiful
28
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
I agree, that was a fantastic idea if I do say so myself. But my personal favourite has to be
pathlib.Path.read_textand its write variant, because I don't even need an explicit context manager anymore.from pathlib import Path ROOT_DIR = Path(__file__).parent DATA_DIR = ROOT_DIR / 'data' QUOTES = DATA_DIR / 'quotes.txt' print(QUOTES.read_text(encoding='utf-8'))5
u/johnnymo1 Jan 23 '22
Oh wow, I didn’t even know about that. That’s another thing I love about pathlib: you don’t need to learn much of it for it it be useful. It just becomes better as you learn it.
0
Jan 23 '22
[deleted]
7
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
Reading, writing, creating, moving, renaming, and deleting. The only thing it can't do in a single step is copying, but for that you can use
shutil.copyor you can read a file and write the contents to a new one.old = Path(...) new = Path(...) new.write_bytes(old.read_bytes())0
Jan 23 '22
[deleted]
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
I don't know, I'm not part of the team developing said module. But if I had to guess there's simply little incentive to do it.
5
3
u/Engineer_Zero Jan 23 '22
Thank you for this. Gonna google pathlib so I can replace my standard glob filewalks.
4
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
If you run into trouble, I'm happy to help.
2
u/Engineer_Zero Jan 23 '22
Thanks man, appreciate it. I use python sparingly and am only a civil engineer; a lot of my code is taken from stack overflow so admittedly some of it could be dated. I have some PDF extraction work coming up this week to automate some inspection work so I’ll have a crack then :)
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
And I'm a mere software engineering student, who just happens to already work for big tech. ;)
2
u/iggy555 Jan 22 '22
What are type hints for beginners?
14
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 22 '22
It's basically information for the developer on what "shape" of data some function expects or might return. You can think of it as supplemental, condensed documentation.
It's very useful when importing something from a library, for instance. You may not instinctively know what some function might do, but if it has type hints implemented that can immediately tell you some useful things about it.
For instance, a developer not used to Python might think
list.sortreturns a sorted list, but if you look at the type hints your IDE might be able to tell you about it,https://i.imgur.com/8m7qMJu.png
you can immediately tell two things; first, it doesn't actually return anything so it's safe to infer it sorts the list in-place, and you can also see what types it expects for any parameters (for instance,
keyis expected to either beNoneor a function/other callable that returns something that implements comparisons).Sometimes you might be working with some data file that needs to be parsed, and the end result may not be immediately obvious. In such cases it's usually helpful to add type hints so that other developers have a rough idea what to expect even without looking at the actual data:
import json from pathlib import Path from typing import Union FilePath = Union[str, Path] def parse_coordinates(file: FilePath) -> list[dict[str, tuple[int, int, int, str]]]: ...In this example you could tell the data is a list of dictionaries, with strings as keys and tuples as values. This is important information for anyone who has to do something with the data, as without this information they'd have to go in blind if they can't directly access the data locally (common on big tech projects)
In a nutshell, they help the developers find corner-cases where they may have overlooked something that could lead to a
TypeError, and in addition to that they help with understanding what kind of data is being passed around.1
1
1
u/FerricDonkey Jan 23 '22
def parse_coordinates(file: FilePath) -> list[dict[str, tuple[int, int, int, str]]]:Also, having a return type that's that explicit (or an argument type if another function expects an argument of that shape) can really help you catch annoying errors before they happen, even as the author of the code. I can't count the number of times pycharm has turned some variable yellow, and I go to look at it it turns out I flubbed the creation of the object or was trying to access something wrong.
Type hints are the best thing ever, and I wish I learned about them years ago.
6
u/skellious Jan 23 '22
Because python doesn't have static typing, you don't need to tell it what type a variable is (int, string, float etc) but type hints allow you to specify it anyway, helping both people using your code and also your IDE to find out if the wrong type of variable is being passed to a function.
1
u/iggy555 Jan 23 '22
Is this something a lot of people do now or only a few?
4
u/FerricDonkey Jan 23 '22
Can't speak for anyone else, but I use type hints for every function I write ever since I learned about them a year or two ago. It makes things so much clearer, especially if you're coming back to a project after a lot of time, and it's really nice to have pycharm turn something yellow when you're passing in a type that will crash your code.
3
u/IamImposter Jan 23 '22
It helps greatly. Sometimes I refactor my code and forget to update code at call sites. Vscode shows tiny little squiggly lines and i know I messed up. What I would have caught at run time, I caught right now.
Though I still haven't learned how to add type hints when a variable can have one of multiple types based on the execution path it followed but it's in my todo list.
1
2
u/GriceTurrble Jan 23 '22
In most applications, they're clues for other developers as to which variable types they shoud expect when using your package.
Some packages, like Pydantic, build upon type hints to create automatic data coercion and validation. If you declare a field in a Pydantic model as an
int, it will try to convert data for that field to int or raise an exception if it cannot.So they're not strictly necessary in most apps, but they are super helpful when you provide good type hinting for other developers to rely on.
1
1
1
u/Xzenor Jan 23 '22
Thanks for pathlib. I was using the os module
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
No problem. It's probably my favourite thing in the entire standard library, personally.
1
u/zxcvbnmike15 Jan 23 '22
I was curious, since dicts are insertion ordered now, is that an easy way to index them by position? I mean, if I want the last value I would think :
my_dict.values()[-1]But that's not the case since values, items, keys all return a iterators. Is :
val_end = list(my_dict.values())[-1]the best way to make this call. Also a dict is the best container for this variable. This is more just an edge case.
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
Is :
val_end = list(my_dict.values())[-1]the best way to make this call.
I haven't really given it much thought as I've never needed a sorted dictionary (so far), but probably yes.
1
u/do_kind Jan 23 '22
How do you manage type hints for functions that return many things, say, return a str, an int and a bool?
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 23 '22
Depends on what you mean. Here's two examples that come to mind:
from typing import Union #1: Function returns a tuple def example() -> tuple[str, int, bool]: return "Hello", 42, True #2: Function returns one of multiple types: def example_2(stuff: str = 'string') -> Union[str, int, bool]: if stuff.lower() == 'string': return 'Hello' if stuff.lower() == 'number': return 42 if stuff.lower() == 'boolean': return True raise ValueError1
u/py_Piper Jan 24 '22
In the new version of ATBS they teach us to use pathlib, but the author mentioned something about not using pathlib for changing directory and/or creating new directories. So it was still recommend to use OS library for this. Can we do everything filesystem related with only pathlib?
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 24 '22
pathlibalone cannot change the current working directory, if that's what you meant. For that you would supplement it withos- though personally I usually don't see the need for doing that anyway as often workarounds exist.As for creating directories,
pathlibcan totally do that. Even recursively.pathlib.Path.mkdirdoes exactly that.1
u/martnym Jan 24 '22 edited Jan 24 '22
Totally agree about not changing the CWD — can't remember the last time I ever needed to do it. Agree about
pathlib, too. Made a decision a while back to try using it every time I felt the need to useos.pathin a conscious effort to learn it — and have felt greatly rewarded for the effort.1
u/py_Piper Jan 25 '22
Yeah perhaps changing current directory isn't as needed as I use trying stuff on the IDLE shell and I just saw your ROOT_DIR, DATA_DIR example, looks like a good work around for moving around if needed.
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 25 '22
I've just gotten into the habit of always using the script as an anchorpoint, and I tend to use
ROOT_DIRas the name for the directory said script is in. But not always - sometimes I actually want to use the name for the project's actual root directory if for some reason I want access to it, in which case I'd useSCRIPT_DIRfor the file instead.As for why uppercase, I like to treat them as constants. Pretty sure there isn't any convention for it, it's just what I've grown accustomed to on my own.
43
u/100721 Jan 23 '22 edited Jan 23 '22
Adding to this, there’s a cool way to debug with f strings. Something like print(f”{my_var=}”) will output the variable name and its value. Short hand of print(f”my_var={my_var}”)
Highly recommend mCoding on YouTube. He’s got some very cool Python tips
17
u/Immotommi Jan 23 '22
Worth noting that f-strings were implemented in 3.6, but the equals syntax was not added until 3.8
6
15
u/ES-Alexander Jan 22 '22
A few that haven’t yet been mentioned:
supercalls in classes now by default pass in the current object, and follow MRO (method resolution order), so generally don’t require arguments. This makes inheritance more general, and easier to set up/define in consistent ways (with less hard-coding).list/set/dict comprehensions (and generator expressions) are a useful way of defining data structures - they’re frequently more readable and more efficient than creating the container and then looping to put the stuff in it, and generally replace
filter/map(e.g.[int(x) for x in strings if x.isnumeric()])walrus/assignment operator (
:=) allows for assigning a name as part of an expression, which can simplify things like while loop setup and conditional executionmatrix multiplier operator (
@) simplifies specifying matrix multiplications with libraries like numpy
3
u/Peanutbutter_Warrior Jan 23 '22
It should be pointed out that list comprehensions aren't lazily evaluated. If you expect to not read a significant amount of the data then the functional methods are a better choice, speed wise.
They're also far better for code golf3
u/ES-Alexander Jan 23 '22
It should be pointed out that list comprehensions aren’t lazily evaluated
That’s what generator expressions are for (e.g.
(int(x) for x in strings if x.isnumeric())). If you need all the data to be accessible at once (e.g. for later random access or whatnot) then it makes sense to put all the data into a suitable container, but if you want lazy evaluation you use the tools that are made for that.Agreed that it’s also possible to achieve that with functional methods (e.g.
map(int, filter(str.isnumeric, strings))), although I personally find that harder to read, and it’s worse again if the filtering or mapping is on a simple expression, because that then requires defining a lambda/partial function (e.g.(x + 3 for x in numbers)vsmap((lambda x: x+3), numbers)ormap(partial(operator.add, 3), numbers)(which also requires two imports)).I don’t tend to play code golf, but it does seem that the functional methods end up with fewer characters, so fair point there.
22
u/omutist Jan 22 '22
8
Jan 22 '22
When I first used this I was expecting it to be a normal switch/case syntax that I've been wanting for so long, but damn I was so impressed with Pythons implementation of it. Extremely powerful.
3
u/legobmw99 Jan 23 '22
Yeah, destructuring match is an idea taken from a few different functional languages. It's much more powerful than switch statements, but IMO the Python version lacks something that I really appreciate in other languages which use it, which is exhaustiveness.
In OCaml for example, if you define a type
Real of real| Int of int | Complex of real * real, and then define something which matches on Real and Int, it will give you an error that says "hey, you forgot Complex here". This is incredibly helpful, especially with complex destructuring5
u/Peanutbutter_Warrior Jan 23 '22
The guaranteed "correctness" of an exhaustive match is nice, but not having it in python feels right. Because of python's dynamic typing, there's almost no way you could actually enumerate every option unless you have an explicit "if none of then => do nothing". I suppose this could have been required, but the lack of boilerplate feels better.
4
u/legobmw99 Jan 23 '22
Oh yeah, I think it's impossible (or meaningless) to provide in a dynamic environment. I suppose tools like MyPy could do it, if the input was declared to have a certain type
6
4
3
u/RobinsonDickinson Jan 22 '22
It's called string interpolation and it is very useful indeed. I believe every language should include string interpolation as a feature, or atleast part of their standard library.
3
u/djdawson Jan 23 '22
Related to your f string discovery, today I learned how to use them to use variables in regular expression search patterns. It's very convenient!
2
2
u/Foreign_Jackfruit_70 ѕɛlf.ƬαughԵ(⌬) Jan 22 '22
sys.stdout.write(f"Yes indeed {f_strings} are my favorite string format")
1
1
5
u/Se7enLC Jan 23 '22
I got burned by them. Got all excited, used them everywhere, and then I had to put my code on a machine with Python 3.5.
Lesson learned: Don't use new features unless they are worth cutting off compatibility with older versions. If it were some fundamentally improved feature I could justify it, but "my print statements took slightly fewer characters" wasn't worth it, so I had to revert all my f-strings to .format().
This was a few years ago now, though, I think it's safe to assume Python 3.6+ now.