Articles
Screencasts
Exercises
Training
Pastebin
Gift
/
Sign Up
Sign In
A demo of some Python 3.12 features!
Editable Code
"""A demo of some Python 3.12 features!""" # f-strings are less restrictive now (they don't have their own parser anymore) embed = ["embed", "f-strings", "in", "f-strings"] backslashes = ["put", "backslashes", "in", "f-string", "replacement fields"] print(f"You can {" ".join(embed)} even with double quotes embedded in double quotes...") print(f"More importantly you can now (finally) {'\n'.join(backslashes)}!") print(f"Or embed {(w:='walruses')}, but please don't use {w} in f-strings.") print(f"""The ability to put { # Re-use previous list because we're lazy " ".join(backslashes).replace("backslashes", "comments") } *might* come in handy though?""") print("On f-string changes:\nhttps://docs.python.org/3.12/whatsnew/3.12.html#pep-701-syntactic-formalization-of-f-strings\n\n") from os.path import commonprefix import pathlib class Path(pathlib.Path): """ You can now subclass pathlib.Path objects to extend their functionality! This was deceptively difficult to do in Python 3.11 and below. """ def common_prefix(self, other): """Return the common prefix between our path and the given path.""" return type(self)(commonprefix((self, other))) path1 = Path("this/is/a/path").resolve() path2 = Path("this/is/another/path").resolve() print( "You can now subclass pathlib.Path objects now too:", path1.common_prefix(path2), ) print("Also Path objects now have a walk method which works like os.walk! 👏") print("And relative_to accepts walk_up=True to act like os.path.relpath!") print("\n") from itertools import batched sentence = """ itertools now has a batched function which is basically the same as a Python Morsels exercise. Can you figure out which one? """ for words in batched(sentence.split(), 6): print(*words) print("\n") print("And of course Python 3.12 is a bit faster than Python 3.11") print("And the error messages have continued improving! https://docs.python.org/3.12/whatsnew/3.12.html#improved-error-messages") print("""Also sqlite3 and uuid both have command-line interfaces now! https://docs.python.org/3.12/library/uuid.html#uuid-cli https://docs.python.org/3.12/library/sqlite3.html#sqlite3-cli""") print("Unicode 15.0.0 is now supported too: \N{PINK HEART} & \N{GOOSE} anyone?")
935 views
Copy
Code copied
Run
in Browser
pym.dev/p/2vxxa/
URL copied
Need to share some Python code?
New Python snippet