Skip to content

Python 3.12: Unpacking New Features and Performance Enhancements

Python 3.12: Unpacking New Features and Performance Enhancements
2024-09-097 min read
41

Python 3.12: Released!!!

Python released its latest version, i.e. python3.12 on October 2, 2023. This release bundles with a lot of enhancements and performance improvements. This time, python has solved the most controversial GIL (Global interpreter Lock). Not only this F strings are also improved and many more let’s know more about it.

What is new in Python 3.12

  1. Improved Error Handling
  2. Enhanced f string usage
  3. Per interpreter GIL
  4. Better garbage collection.
  5. Improved memory management.
  6. Supports Linux perf profiler.

Error handling in Python 3.12

With this python version, we get better error messages and suggestions to solve the error, Here are a few examples with which you get better idea

	class User:
	    def __init__(self, name, age):
	        self.name = name
	        self.age = age
	    def print_details(self):
	        return f"{self.name} {age}"
 
	user = User("Witty coder", 25)
	print(user.print_details())

Output -->

NameError: name 'age' is not defined. Did you mean: 'self.age'?

In the above code, we are trying to return a value that is defined in the constructor, and we are using it in the class method without self, so instead of raising NameError Python suggests that .age is an attribute available as an attribute, so you can use the instance self. age instead of the local name, age.

Aditionally, the import messages are also very much enhanced and are now self-explanatory, it suggest correct library, function or any syntactical error while import. Below are few examples of same-

  1. If you missed any import then errror message suggests to import the right module like did you forgot to import foo.
  2. If syntax of import is wrong then also we get a message with correct syntax. Here is a better explanation of same suppose you wrote import foo from bar then it returns an error asking if you meant from bar import foo.

The suggestions that you’ve seen in these examples are all new in Python 3.12. Together, they make Python a little more user-friendly and saves our time.

F-string with more Power

F-strings or formated string in python helps us embed expressions inside string literals whichgets evaluated at the run time, this string is prefixed with f and and the expressions are put in a pair of curli braces { } . Heres a syntax of same

name = "Witty Coder"
s = f"Length name is {len(name)}" # length will be evaluated at the run time

Now with previous versions face an error when we try to add quotes in f-string below is a demonstration of it

d = {"key":"value"}
print(f"Value of key is d["key"]")

Output -->

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 2
    print(f"Value of key is d["key"]")
          ^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

Until now, we cannot use a backslash character \ with f-string expression. With the latest update we can now use backslashes in f-string expressions as in any other expression:

names = ["Varanasi", "Delhi", "Ayodhya"]
print(f"City names:
 {"
 ".join(names)}")
 

Output -->

City names:
Varanasi
Delhi
Ayodhya

In above code example we can see that the code is giving proper output even after using the backslash.

Per-Interpreter GIL

The introduction of Per-Interpreter GIL into Python 3.12 is an extremely important change for multi-threaded applications. In the earlier version, Python’s Global Interpreter Lock (GIL) ensured that only one thread was able to execute bytecode at any given moment.

This restricted python to use limited core full performance of the cpu was not achieved. Not after this improvement multi-threaded programs could achieve on performance, especially in a multi-core system. Today, each instance of the Python interpreter has its own GIL.

This allows running thousands of threads in disjoint Python processes concurrently, hence improving performance for multi-threaded applications that are spread out across separate processes. This move opens avenues to much better parallelism since threads no longer have to wait on some global lock before proceeding with the operation.

This implies improvement in scalability and concurrency in applications to the Python developer, especially in CPU-bound tasks.

Garbage collection

This is with better garbage collection, so Python 3.12 is more efficient now in managing its memory. The new garbage collector reduces memory fragmentation when objects are created and de-destroyed in many programs. It prevents memory leaks because it can identify and clear unused memory quite fast and accurately.Another good thing is a reduction in overhead in managing memory, which helps improve application performance in general.

It makes the developers easier to run their applications, particularly longer running processes or larger data-handling applications. This garbage collection is fine-tuned and minimizes memory mishaps and maximizes the efficiency of usage memory for applications.

Supports Linux Perf Profiler

Built-in support libraries for Python 3.12 introduce a powerful Linux perf profiler, a tool that may be quite handy for developers to get down-low on CPU and memory use of their code, assisting in optimizations by pointing out bottlenecks and inefficiencies. This means native Python developers have direct low-level performance data available to them without requiring external tools.

It makes it easier to detect performance issues in applications as being CPU-intensive and fine-tune code for better efficiency. Support for Linux perf profiler enhances Python’s capability for high performance applications that could be optimized with greater precision and confidence across the Linux platforms.

Improved Memory Management

The management of memory has also been enhanced to decrease the usage of memory and enhance the efficiency of the process.

Key improvements involve how Python distributes and deallocates memory, and it helps a lot in better management of the memory in long-running programs.

The latest features in memory management try to minimize fragmentation as a consequence of the process of memory allocation followed by memory release in small chunks, where huge portions of memory go to waste.

This makes Python programs run that much more smoothly, in particular applications that constantly create and destroy a lot of objects. Memory handling in Python is also faster and more reliable, with diminished chances of memory problems, such as leaks and crashes. So what does this really mean? Better performance, especially for memory-intensive applications.

Conclusion

To sum it up, Python 3.12 is a great update packed with features that make development faster, easier, and more enjoyable. From improved developer experience, to performance boosts it’s clear that this release is about more than just syntax changes. If you haven't taken the plunge yet, now’s the time to explore what Python 3.12 has to offer. Happy coding, everyone!

FAQs

  1. What is the most significant performance improvement in Python 3.12?

    • Latest Python 3.12 has shown significantly better execution speed, with some workloads running 15-30% faster. Reason being the per interpreter GIL.
  2. Are there any backwards compatibility issues with Python 3.12?

    • Python 3.12 keeps strong backward compatibility, you must test your code to find out whether you are using any deprecated functionality.
  3. What new modules were added in Python 3.12?

    • Python 3.12 has introduced several new modules that facilitate various programming tasks without the need for external libraries.
  4. How do the new error messages help developers?

    • The improved error messages with suggestions provide clearer diagnostics and fix recommendations, helping both new and experienced developers debug faster.
  5. Will my existing projects work with Python 3.12?

    • Most existing projects should work, but it’s crucial to check for any deprecated features and thoroughly test your code after the upgrade.

Keep Reading