17 Apr 2025
Planet Python
Everyday Superpowers: Preventing painful coupling
This is the second entry in a five-part series about event sourcing:
- Why I Finally Embraced Event Sourcing-And Why You Should Too
- What is event sourcing and why you should care
- Preventing painful coupling (this page)
- Event-driven microservice in a monolith
- Get started with event sourcing today
In the first article, I introduced this series with the spark that made me so happy to finally try event sourcing.
In the last article, I showed you what event sourcing is.
In this article, I will show you how and why I've completely changed the way I code.
Have you ever worked on a project where adding a simple feature felt like defusing a bomb-one wrong move, and the whole system might break? You're not alone. In 1979, the industry was reeling from how hard it was to modify software.
I came across an article from the Association for Computing Machinery 1979 that talked about a crisis in the software community: how expensive it was to modify existing software:
- quote
- Another component of the software crises is less commonly recognized, but, in fact, is often more costly… namely, the extreme difficulty encountered in attempting to modify an existing program… The cost of such evolution is almost never measured, but, in at least one case, it exceeded the original development cost by a factor of 100.
- attribution
- Terry Winograd, Beyond Programming Languages, Communications of the ACM, July 1979 Volume 22 Number 7
Could you imagine asking a team of developers to adjust a program and having to pay 100x what you paid them to write it in the first place?
I've been on projects where I can start to see how this happened, but it's crazy this is where our industry came from.
This was untenable, and many smart people discussed how to improve software writing. A lot of progress was made in the 1980s and 1990s.
One of the main discoveries was that unwanted coupling made software more complex and more challenging to refactor. This was reflected in several pieces of the time, including Martin Fowler's curation of refactoring methods in his seminal book published in 1999 and Robert Martin's curation of the SOLID principles in the early 2000s.
Despite these discoveries, the challenges of modifying software haven't disappeared. Instead, they've taken on new forms, often exacerbated by the industry's rapid growth.
In the 2000s, the number of developers grew explosively, and the percentage of people who knew how to teach these concepts became a tiny percentage of the population. As a result, most developers have only heard of these techniques and patterns, like SOLID, but few truly understand or practice them[oops]{For example, I've noted a trend of programing resumes announcing they are skilled in OOPS.}.
Most developers are not familiar with or practiced in controlling complexity or refactoring to reduce unwanted coupling.
I imagine the 100x penalty for adding features to projects is a thing of the past, but I know of a project that was in trouble in a similar way.
This team struggled with slow development cycles because every feature required each developer to make changes across multiple layers, including database schema, API, UI state, and frontend components. Merge conflicts were constant, and progress slowed to a crawl. In this case, they ultimately found success by reducing complexity and shifting their React front end to HTMX.
But switching frameworks isn't always an option. A deeper change is needed: a way to structure software that naturally reduces coupling.
One solution is to continue to educate people about refactoring, software patterns, and good habits-and define times to practice these new skills. I've been impressed with Emily Bache's Samman Technical Coaching Society approach, which truly gives developers the space to learn and practice these skills on their codebase as a team.
I believe the Samman Society and other like-minded technical coaches are making an impact in the industry. But they can only work with so many teams. What if we could fundamentally change how we structure our applications to reduce this complexity at its source?
In the last few months, I've been convinced that there's another option: changing how we write apps to reduce coupling.
The excellent book Cosmic Python (aka Architecture Patterns in Python) explains coupling in this way:
- quote
- In a large-scale system, we become constrained by the decisions made elsewhere in the system. When we're unable to change component A for fear of breaking component B, we say that the components have become coupled. Locally, coupling is a good thing: it's a sign that our code is working together, each component supporting the others, all of them fitting in place like the gears of a watch. In jargon, we say this works when there is high _cohesion_ between the coupled elements. Globally, coupling is a nuisance: it increases the risk and the cost of changing our code, sometimes to the point where we feel unable to make any changes at all. This is the problem with the Ball of Mud pattern: as the application grows, if we're unable to prevent coupling between elements that have no cohesion, that coupling increases superlinearly until we are no longer able to effectively change our systems.
- attribution
- Cosmic Python
Unwanted coupling is easy to accidentally introduce into your application. Most of the time, we couple things together because it seems like a good idea at the time. We don't know if it's unwanted until some time in the future.
One way to tell if your code has unwanted coupling is to test it. If the test case is easy to make, you probably have an healthy level of coupling. Testing is the canary in the coal mine for coupling.
Before I understood how to deal with coupling, I watched it take over on one project, where a function grew day after day, as we added new features to it, trying to meet a deadline. It started out processing some data. Then, we needed to add a feature to notify people when it finished. That was followed by some additional processing requirements and API calls to augment data. We also decided to add code to notify us if something failed in some of these steps.
What started out as a relatively simple function turned into over 100 lines of code with several different workflows braided together. I could tell something was off by the number of parameters we had and how hard it was to test, but I had no idea how to unwind it.
So how do we reduce unwanted coupling? I mentioned above that one way is to learn how to make great software, how to refactor it, and practice it many times outside of normal project work.
In the last year, I've come across articles, podcasts and videos that has convinced me to change the way I work to help keep coupling low.
There are three key practices work together to keep complexity under control while enabling flexible and scalable solutions: event modeling, vertical slice architecture, and event sourcing.
Let's look at these one at a time.
Event modeling is a documentation method that shows how data flows through a system and the domain constraints in play.
It might seem weird to start off with a documentation method, but by starting with getting the developers on the same page as the business stakeholders, you eliminate many surprises, and get a few more benefits.
Event modeling grew from event storming, a documentation workshop technique that extracts complex business domains from stakeholders and transforms them into domain-driven design concepts that developers can use.
As a user of event storming, Adam Dymitruk noticed that business stakeholders were left behind During event storming sessions once the conversation became more about bounded contexts and other technical implementation details.
After many iterations, he unveiled event modeling in 2020. It's a documentation method that removes much of the implementation detail. Instead, it highlights the most important thing: data, and how it enters, gets used by, and exits the system, as well as domain rules that affect it, all in a simple visual language with four patterns to master.
Additionally, the application's lifecycle is segmented into individual slices representing one process step. Each slice maps to a slice in the vertical slice architecture that we'll discuss below.
Below is an example event modeling diagram showing part of the lifecycle of a shopping cart application. The blue boxes are commands. They represent an intent to change the state of the system. This is where domain rules are enforced, and a command either generates an event or an exception.
By creating an event, this changes the state of the system. Other slices listen to events and populate views (the green boxes). These can be caches, database tables, CSV files, or anything that formats data in a way that will be consumed.
Having done a couple event modeling diagrams, what I like about them are:
- Being able to understand the domain more as the diagram comes together
- Uncovering needs early in an project, instead of late in the process when you're implementing the feature under time pressure.
- Making it easier for everyone-developers and stakeholders-to stay aligned
I've been conditioned by the majority of my projects and more senior teammates to expect the projects I work on to be organized with similar code together. The views, services, and models would be grouped by type and placed into a folder bearing its name.
Contrasting this practice, vertical slice architecture organized code by feature. For example, if we're working on a shopping cart application. A vertically-sliced project would have folders with names like `add_item`, `checkout`, `remove_item`, and `list_items`.
In each of these folders, you would find the UI, data access code, and business logic related to those features.
I've found this to be a great way to work. Instead of hunting around the project or tracing through the code from the endpoint down into every layer that gets called, I can just open the folder for the feature and have a very good idea what file to open.
Adam Dymitruk's group has seen great productivity increases from adopting vertical slice architecture. He's mentioned having ten developers working independently on slices and not having a single merge conflict.
When all the code for a feature is in one folder, suddenly adding a feature to a "normal" project feels like performing shotgun surgery.
I like a lot about object-oriented programming, especially with an imperative shell and a functional core. With well-designed OOP software, you can trust that by editing one part of the code, you won't introduce a bug in another part. It seems I've never worked on well-designed OOP code-or I'm just that good at finding the weak spots of our designs.
With an event modeling diagram and the direction to implement a specific vertical slice, a developer can concentrate on what data is entering their slice (whether from the user, an external provider, a read model, or by subscribing to events), handle the business case, and then publish the events expected from their slice or populate a database table as needed.
A event-sourced project with vertical slice architecture, each slice is isolated from the other, communicating through predefined events and views. It's a really cool pattern.
It's important to note that you could reduce coupling without event sourcing. Communicating well with event modeling diagrams and an even-driven, vertically sliced architecture, you can have similar gains.
The three practices together have proved powerful for me. In the next article, I'll show you more detail how, while also having the benefits of an event-driven microservice and a monolith.
17 Apr 2025 4:38pm GMT
PyCon: Community Organizer Summit and PSF & Meetups Discussion
Calling all community organizers! We want to sit down together and share what's going well, what new tricks we've learned, and what's been challenging in the area of organizing Python and Python adjacent communities. So if you're attending PyCon US this year and you run a local Python meet-up, help organize a regional conference, or facilitate peer learning through workshops or hack nights, we hope you will join us at the Community Organizer Summit and the PSF & Meetups Discussion.
Community Organizer Summit: 10:30 am - 1 pm on Saturday, May 17th
PSF & Meetups Discussion: 1pm - 2pm on Sunday, May 18th
Saturday's Community Organizer Summit kicks off with a keynote and then three short "Show & Tell" slots, for which the CFP is open now. After the more formal sessions, we'll break into unconference discussions, so be sure to bring your ideas. If you're not able to make it to Pittsburgh but you want to join the ongoing conversation about conference organizing, please consider joining the bi-monthly Conference Chats on Discord. Thanks so much to Mason Egger, Heather White and Kevin Horn for organizing the Summit!
Sunday's PSF & Meetups Discussion is organized by the PSF board and is intended to kick off a more collaborative and purposeful era of Python community organizer knowledge sharing! Community organizer meetups have been happening casually at PyCon US and (more famously) at EuroPython for a few years now. We're looking to make this year's PyCon US session into a jumping off point for a global conversation that we hope to see happen regularly in lots of places around the world, as well as online. If you've got ideas or want to be involved in this conversation, please email community-organizing@pyfound.org
This is not just for experienced organizers! Looking to start a community and want to learn from a group of awesome people? Come join us!
17 Apr 2025 10:13am GMT
Django Weblog: Run your tests against Django's main!
This is the blog version of a talk! If you prefer, watch the recording on YouTube:
Sage Abdullah - Run your tests against Django's main! - Django London Meetup
Django is known for its stability. The framework makes a strong commitment to API stability and forwards-compatibility, ensuring that developers can rely on it for building long-term, maintainable projects. A key aspect of this commitment involves extensive testing and structured releases-an area where testing by Django users can significantly enhance Django's reliability. Here's a closer look at how this works, and how you can contribute 🤝.
How Django stays stable
Django's stability is upheld through rigorous testing. As of Django 5.2, there are more than 18,000 tests run against all officially supported database backends, Python versions, and operating systems. Additionally, Django follows a well-structured deprecation policy, ensuring that public APIs are deprecated over at least two feature releases before being removed.
The feature release schedule is systematic and structured:
- Active development happens on the
main
branch. - A stable branch (for example
stable/5.2.x
) is forked when an alpha release is made. - After a month, the beta release follows, where only release-blocking bug fixes are allowed.
- A month later, a release candidate (RC) is published, marking the translation string freeze.
- If no critical bugs are found, the final release is published after a couple of weeks.
With this structured approach, Django ensures that releases are stable. However, bugs can and do occasionally slip through the cracks!
Catching issues early
The best time to catch issues is before they reach the final release. Ideally, potential bugs should be caught at the pull request stage, but keeping up with all changes is challenging. This is where the community can help-by running their tests with Django's main
branch.
How you can help
You can set up your test suite to run with Django's main
branch in your tests pipeline. Here's an example using GitHub Actions, a popular Continuous Integration platform:
test:
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
matrix:
include:
- python: "3.13"
django: "git+https://github.com/django/django.git@main#egg=Django"
experimental: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- run: pip install -r requirements.txt
- if: ${{ matrix.experimental }}
run: pip install "${{ matrix.django }}"
- run: python -Wd manage.py test
:root[data-theme="light"] .highlight .l { color: var(--code-fg); }
If you maintain a Django package, you likely already test with multiple Django versions. Adding the main
branch ensures that your project stays ahead of potential breaking changes.
Why this helps you
Running tests with Django main
allows you to detect when changes in Django break your project. Sometimes, this happens due to the removal of internal APIs (that were never intended for reuse outside Django 🙈). If your tests fail, you can identify which commit caused the issue and adjust your code accordingly.
For example, on the Wagtail CMS project, recently caught an issue when an internal class, SubqueryConstraint
, was removed from Django. This wasn't a bug in Django-it was the removal of an internal workaround that was no longer needed. If your project relies on internal APIs, testing against main
is crucial to avoid surprises.
Why this helps Django
Testing with main
doesn't just help your project-it helps Django too. Sometimes, your tests may fail due to legitimate regressions in Django that its test suite doesn't cover. Reporting these issues ensures they get fixed before the next release.
For example, just two days before Django 5.2 alpha was released, Wagtail tests on main
helped detect a bug where calling .full_clean()
on a child model in a multi-table inheritance setup triggered an unintended database query. This regression was promptly fixed, ensuring a smoother release for all users.
Take action: test against Django's main and report issues
By running your tests against Django's main
branch and reporting any issues you find, you contribute to a more stable framework for everyone. It's a small step that makes a big impact.
So, take a few minutes today to update your automated tests setup and help keep Django as reliable as ever!
17 Apr 2025 9:00am GMT
EuroPython: Tickets, Sessions, & Call for 2026 Host Venues!
Hello, Pythonistas! 🐍
Tickets are on sale now! You can get your tickets at europython.eu/tickets
📣 Programme
Keynote Speakers
We are excited to announce three more keynote speakers!
Sebastián Ramírez
Sebastián is the creator and maintainer of several widely used open-source Python libraries, including FastAPI, Typer, SQLModel, and Asyncer. His work focuses on tools for building web APIs, command-line interfaces, and working with data models in Python.
He has collaborated with teams and companies across Latin America, Europe, the Middle East, and the United States, working on systems involving APIs, distributed computing, and machine learning.
Currently, Sebastián works full-time on the development and maintenance of his open-source projects.
Brett Cannon
Brett has been a Python core developer since 2003 and has contributed to just about every corner of the language. He's one of the most prolific PEP authors, the creator of importlib, and played a major role in the Python 2 -> 3 transition and the creation of pyproject.toml.
He served on the inaugural Python Steering Council and remained on it for five years, guiding the language through some of its most critical transitions.
But beyond code, Brett is known for his love of the Python community - "I came for the language, but I stayed for the community". He's a former PSF board member and a recipient of the Frank Willison Award.
Petr Baudiš
Petr Baudiš is a co-founder and CTO of Rossum, a SaaS deep tech scaleup that focuses on automating document-based B2B transactional communication. He co-invented Rossum&aposs unique AI engine and currently oversees Rossum&aposs R&D and product engineering. In the past, Petr led multiple AI research and deep learning projects in academia as well as in commercial environments. His work was used by companies like Google DeepMind, Novartis, Seznam.cz and countless others.
Petr&aposs past exploits include building one of the key predecessors of AlphaGo, working with Linus Torvalds as one of the founding developers of Git, and leading many other open-source projects.
Sessions
Our session list is live! 🎉 https://ep2025.europython.eu/sessions/
🎤 Speaker Mentorship
Accepted Proposals
We're excited to share that 44 proposals were submitted by the mentees and 8 have been accepted! We're incredibly proud of everyone who took the time to submit a proposal-your creativity, passion, and dedication are what make this community so special. Thank you for helping us shape an inspiring and diverse conference program. We can't wait to see you in Prague! 🐍💛
First Time Speakers' Workshop
Whether you&aposre preparing to present at EuroPython 2025 or any other conference or your talk proposal wasn&apost accepted this year, we warmly invite you to our First-Time Speakers&apos Workshop. Join us online via ZOOM on June 4, 2025, at 18:00 CEST to gain essential presentation skills, practical tips, and valuable insights from experienced speakers. This supportive session also aims to inspire you and strengthen your future conference proposals. You can find out more details here: https://ep2025.europython.eu/programme/mentorship/
Register now: https://forms.gle/T8rc73sbyu3KbLNKA
We look forward to supporting your speaking journey!
💰 Sponsorship
If you&aposre passionate about supporting EuroPython and helping us make the event accessible to all, consider becoming a sponsor or asking your employer to join us in this effort.
By sponsoring EuroPython, you're not just backing an event - you&aposre gaining highly targeted visibility and the chance to present your company or personal brand to one of the largest and most diverse Python communities in Europe and beyond!
We offer a range of sponsorship tiers, some with limited slots available. Along with our main packages, there are optional add-ons and optional extras.
👉 More information at: https://ep2025.europython.eu/sponsorship/sponsor/
👉 Contact us at sponsors@europython.eu
EuroPython Society
🏰 Call for Venues - EuroPython 2026
Are you a community builder who dreams of bringing EuroPython to your city? The Call for Venues for EuroPython 2026 is now open!
If you want to propose a location on behalf of your community, please fill in the following form: https://forms.gle/ZGQA7WhTW4gc53MD6
📊 Board Report
The EuroPython conference wouldn't be what it is without the incredible volunteers who make it all happen. 💞 Behind the scenes, there's also the EuroPython Society-a volunteer-led non-profit that manages the fiscal and legal aspects of running the conference, oversees its organization, and works on a few smaller projects like the grants programme. To keep everyone in the loop and promote transparency, the Board is sharing regular updates on what we're working on.
The March board report is ready: https://www.europython-society.org/board-report-for-march/
💞 Community Outreach
Prague Python Meetup Pyvo
A big thank you to Jakub Červinka for giving a lightning talk about EuroPython at the Prague Pyvo meetup!
PyCon US
We're happy to share that EuroPython will have a booth at PyCon US this year! If you're attending, come over to say hi-pick up some stickers, meet members of our community, and learn more about our initiatives and upcoming plans.
PyCon DE & PyData, DjangoCon Europe
We're proud to be supporting both events this year! You'll find EuroPython stickers in the community area-stop by to pick some up and connect with fellow community members while you&aposre there.
Brno Python Pizza
We recently supported Brno Python Pizza, which took place this February in Brno. The organizers shared a lovely write-up about the event, which you can read here: https://www.europython-society.org/brno-python-pizza-great-things-come-in-threes/
💞Upcoming Events in the Python Community
- PyCon Lithuania, Vilnius, April 23-25 https://pycon.lt/
- DjangoCon Europe, Dublin, April 23-27 https://2025.djangocon.eu/
- PyCon DE & PyData, Darmstadt, April 23-25 https://2025.pycon.de
- PyCamp España 2025, Sevilla, 01 - 04 May https://pycamp.es/
- Pycon Italia, Bologna, May 28-31 https://2025.pycon.it/en
- EuroPython, Prague, 14 July-20 July https://ep2025.europython.eu
- EuroSciPy, Kraków, August 18-22 https://euroscipy.org/2025/
- PyCon Greece 2025, Athens, Greece, 29-30 August https://2025.pycon.gr/en/
- PyCamp CZ 25 beta, Třeštice, September 12-14 https://pycamp.cz/
- Pycon UK, Manchester, September 19-22 https://2025.pyconuk.org/
- PyCon Estonia, Tallinn, October 2-3 https://pycon.ee/
- PyCon Sweden, Stockholm, October 30-31 https://pycon.se/
🐣 See You All Next Month
And in the meantime, follow us on social media:
- LinkedIn: https://www.linkedin.com/company/europython/
- X: https://x.com/europython
- Mastodon: https://fosstodon.org/@europython
- BlueSky: https://bsky.app/profile/europython.eu
- YouTube: https://www.youtube.com/@EuroPythonConference
17 Apr 2025 5:00am GMT
16 Apr 2025
Planet Python
Real Python: How to Exit Loops Early With the Python Break Keyword
In Python, the break
statement lets you exit a loop prematurely, transferring control to the code that follows the loop. This tutorial guides you through using break
in both for
and while
loops. You'll also briefly explore the continue
keyword, which complements break
by skipping the current loop iteration.
By the end of this tutorial, you'll understand that:
- A
break
in Python is a keyword that lets you exit a loop immediately, stopping further iterations. - Using
break
outside of loops doesn't make sense because it's specifically designed to exit loops early. - The
break
doesn't exit all loops, only the innermost loop that contains it.
To explore the use of break
in Python, you'll determine if a student needs tutoring based on the number of failed test scores. Then, you'll print out a given number of test scores and calculate how many students failed at least one test.
You'll also take a brief detour from this main scenario to examine how you can use break
statements to accept and process user input, using a number-guessing game.
Get Your Code: Click here to download the free sample code that shows you how to exit loops early with the Python break keyword.
Take the Quiz: Test your knowledge with our interactive "How to Exit Loops Early With the Python Break Keyword" quiz. You'll receive a score upon completion to help you track your learning progress:
Interactive Quiz
How to Exit Loops Early With the Python Break KeywordIn this quiz, you'll test your understanding of the Python break statement. This keyword allows you to exit a loop prematurely, transferring control to the code that follows the loop.
Introducing the break
Statement
Before proceeding to the main examples, here's a basic explanation of what the break
statement is and what it does. It's a Python keyword that, when used in a loop, immediately exits the loop and transfers control to the code that would normally run after the loop's standard conclusion.
You can see the basics of the break
statement in a simple example. The following code demonstrates a loop that prints numbers within a range until the next number is greater than 5:
>>> for number in range(10):
... if number > 5:
... break
... print(number)
...
0
1
2
3
4
5
This short code example consists of a for
loop that iterates through a range of numbers from 0
to 9
. It prints out each number, but when the next number is greater than 5
, a break
statement terminates the loop early. So, this code will print the numbers from 0
to 5
, and then the loop will end.
As break
statements end loops early, it wouldn't make sense for you to use them in any context that doesn't involve a loop. In fact, Python will raise a SyntaxError
if you try to use a break
statement outside of a loop.
A key benefit of using break
statements is that you can prevent unnecessary loop iterations by exiting early when appropriate. You'll see this in action in the next section.
Breaking Out of a Loop With a Set Number of Iterations
Imagine you're a teacher who evaluates the scores of your students. Based on the scores, you want to determine how many tests each student has failed. The following example demonstrates how you might accomplish this task using a for
loop to iterate through the students' test scores:
>>> scores = [90, 30, 50, 70, 85, 35]
>>> num_failed_scores = 0
>>> failed_score = 60
>>> for score in scores:
... if score < failed_score:
... num_failed_scores += 1
...
>>> print(f"Number of failed tests: {num_failed_scores}")
Number of failed tests: 3
Read the full article at https://realpython.com/python-break/ »
[ Improve Your Python With 🐍 Python Tricks 💌 - Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
16 Apr 2025 2:00pm GMT
PyCharm: PyCharm 2025.1: Unified PyCharm, Free AI Tier, Junie Release, and More!
PyCharm 2025.1 brings major updates to improve your development experience.
PyCharm is now a unified product, combining PyCharm Professional and Community Edition. Version 2025.1 also brings a free AI tier, the public release of Junie, the launch of Cadence, significant Jupyter enhancements, support for Hatch, Data Wrangler, and many other improvements.
Get the latest version from our download page or update through our free Toolbox App.
Read this blog post to learn more about the updates.
Prefer video? Get an overview of the major news and improvements in this video:
PyCharm is now one powerful, unified product!
PyCharm is now one powerful, unified product! Its core functionality, including Jupyter Notebook support, will be free, and a Pro subscription with additional features will be available.
Starting with the 2025.1 release, every user will get instant access to a free one-month Pro trial, so you'll be able to access all of PyCharm's advanced features right away. After the trial, you can choose whether to continue with a Pro subscription or keep using the core features for free. Learn more about the change in this blog post.
Junie - your personal coding agent Pro
Junie, the coding agent by JetBrains, is now available in PyCharm via JetBrains AI. Junie autonomously plans, writes, refines, and tests code to make your development experience smooth, efficient, and enjoyable. It handles tedious tasks like restructuring code, creating tests, and implementing refinements, so you can focus on bigger challenges and innovation.
PyCharm goes AI
JetBrains AI has received a major upgrade, bringing both AI Assistant and the coding agent Junie under a single subscription. With this release, all JetBrains AI features are accessible for free in PyCharm Pro, with unlimited use for some, such as code completion and local model support, and limited credit-based access to others.
We're also introducing a new subscription system that makes it easy to scale up as needed with the AI Pro and AI Ultimate tiers. Other highlights of this release include smarter completion, advanced context awareness, and support for Claude 3.7 Sonnet and Gemini 2.0 Flash. Head to the What's New page to learn more about the latest AI features.
Cadence - effortless cloud execution for ML workflows Pro
We're introducing Cadence. You can now run your machine learning code on powerful cloud hardware directly from PyCharm in minutes - no complex setup or cloud expertise is required. The Cadence plugin simplifies ML workflows, allowing you to focus on your code while leveraging scalable computing resources.
Data Wrangler Pro
We've implemented Data Wrangler, a powerful tool to help Python data professionals streamline data manipulation and focus on higher-level analysis. Use the interactive UI to perform common dataframe transformations - like filtering, cleaning, handling outliers, and more - without writing repetitive code.
You can view and explore column statistics, generate Python code for transformations automatically, track the history of changes, export data easily, and insert transformations as new cells in your notebook.
SQL cells in notebooks Pro
PyCharm 2025.1 introduces SQL cells. This new cell type allows you to query databases, dataframes, and attached CSV files in Jupyter notebooks and automatically save query results to pandas DataFrames.
We've also introduced many other improvements to enhance the Jupyter notebook experience. Learn more about them in the What's New.
Support for Hatch
We're introducing support for Hatch, a modern and extensible Python project manager from the Python Packaging Authority (PyPA). Hatch can automatically migrate setuptools configurations, create isolated environments, and run and publish builds, making Python package management more efficient.
PyCharm also allows you to create new projects managed by Hatch. The IDE will automatically recognize Hatch projects when they are imported from a local machine or a remote source.
Looking for more?
- Visit our What's New page to learn about other 2025.1 features and the latest bug fixes.
- Read the release notes for the full breakdown of the changes.
- If you encounter any problems, please report them via our issue tracker so we can address them promptly.
We'd love to hear your feedback on PyCharm 2025.1 - leave your comments below or connect with us on X.
16 Apr 2025 1:58pm GMT
PyCharm: PyCharm, the Only Python IDE You Need
Estimated reading time: 3 minutes
PyCharm is now one powerful, unified product! Its core functionality, including Jupyter Notebook support, will be free, and a Pro subscription will be available with additional features. Starting with the 2025.1 release, every user will get instant access to a free one-month Pro trial, so you'll be able to access all of PyCharm's advanced features right away. After the trial, you can choose whether to continue with a Pro subscription or keep using the core features for free.
Previously, PyCharm was offered as two separate products: the free Community Edition and the Professional Edition with extended capabilities. Now, with a single streamlined product, you no longer need to choose. Everything is in one place, and you can seamlessly switch between core and advanced features within the same installation whenever you need to.
💡 What's new?
✅ One product for all developers
You no longer need to worry about additional downloads or switching between editions. PyCharm is now a single product. Start with a month of full Pro access for free, and then keep using the core features at no cost. Upgrade to Pro anytime within the same installation.
🎓 Free Jupyter Notebook support
PyCharm now offers free Jupyter support, including running, debugging, output rendering, and intelligent code assistance in notebooks. It's perfect for data workflows, no Pro subscription required. However, a Pro subscription does offer more advanced capabilities, including remote notebooks, dynamic tables, SQL cells, and others.
🚀 Seamless access to Pro
With every new major PyCharm release (currently three times a year), you will get instant access to a free one-month Pro trial. Once it ends, you can continue using the core features for free.
🛠️ One product, better quality
Focusing on a single PyCharm product will help us improve overall quality, streamline updates, and deliver new features faster.
What does it mean for me?
🐍 I'm a PyCharm Community Edition user
First of all, thank you for being part of our amazing community! Your feedback, passion, and contributions have helped shape PyCharm into the tool it is today.
Nothing is going to change for you right away - you can upgrade to PyCharm Community 2025.1 as usual. Alternatively, you may choose to manually switch to the new PyCharm immediately and keep using everything you have now for free, plus the support for Jupyter notebooks.
Starting with PyCharm 2025.2, we'll offer a smooth migration path that preserves your current setup and preferences. PyCharm Community 2025.2 will be the final standalone version, and, from 2025.3 onward, all Community Edition users will transition to the unified PyCharm experience.
Rest assured - our commitment to open-source development remains as strong as ever. The Community Edition codebase will stay public on GitHub, and we'll continue to maintain and update it. We'll also provide an easy way to build PyCharm from source via GitHub Actions.
Have more questions about what's next? Read our extended FAQ for more details.
👥 I'm a PyCharm Professional Edition user
Nothing changes! Your license will automatically work with the new single PyCharm product. Simply upgrade to PyCharm 2025.1 and continue enjoying everything Pro has to offer.
🆕 I'm new to PyCharm
You can start right away with the new single PyCharm product. You'll get a free one-month Pro trial with full functionality. After that, you can purchase a Pro subscription and keep using PyCharm with its full capabilities, or you can continue using just the core features - including Jupyter Notebook support - for free. Download PyCharm now.
16 Apr 2025 12:11pm GMT
Real Python: Quiz: How to Exit Loops Early With the Python Break Keyword
In this quiz, you'll test your understanding of the Python break
statement. This keyword allows you to exit a loop prematurely, transferring control to the code that follows the loop.
[ Improve Your Python With 🐍 Python Tricks 💌 - Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
16 Apr 2025 12:00pm GMT
15 Apr 2025
Planet Python
Python Morsels: Practical uses of sets
Sets are unordered collections of values that are great for removing duplicates, quick containment checks, and set operations.
What are sets?
Like lists, sets are collections of values:
>>> fruits = {"apples", "strawberries", "pears", "apples"}
But unlike lists, sets can't contain duplicate values:
>>> fruits
{'apples', 'pears', 'strawberries'}
And sets are also unordered, meaning the values within a set may move around as new items are added to the set:
>>> fruits.add("limes")
>>> fruits
{'apples', 'pears', 'lime', 'strawberries'}
Sets are like dictionaries without values
Have you ever found yourself …
Read the full article: https://www.pythonmorsels.com/practical-uses-of-sets/
15 Apr 2025 11:15pm GMT
PyCoder’s Weekly: Issue #677: __dict__, Streamlit, Boolean Expressions, and More (April 15, 2025)
#677 - APRIL 15, 2025
View in Browser »
Using Python's .__dict__
to Work With Attributes
In this tutorial, you'll dive deeper into the .__dict__
attribute in Python objects. This attribute is a dictionary-like object that holds writable class or instance attributes. It allows you to manage attributes at a low level, making your classes flexible and efficient.
REAL PYTHON
Create Your First App With Streamlit
This tutorial shows you how to start building Streamlit data science apps with Python. Streamlit is an open-source Python library that makes it easy to create and share custom web apps for machine learning and data science.
MARTIN FITZPATRICK
Build AI Agents With 300+ APIs
Nango is an open source platform that lets you build AI applications with 300+ APIs. We offer hundreds of pre-built integrations, customizable in code, and developer tooling purpose built for scaling and maintaining integrations. Try Nango for free →
NANGO INC. sponsor
Refactoring Long Boolean Expressions
This article shows you how you can improve the readability of long boolean expressions by splitting your code, naming sub-expressions, or rewriting your Boolean logic.
TREY HUNNER
Articles & Tutorials
How to Build Hot Module Replacement in Python
Django's dev server, uvicorn, and others support hot-loading by restarting the service. For large programs this can be time consuming. This article shows you how to track just what needs to be reloaded and minimize the refresh to only those modules.
GAUGE
Is Python Code Sensitive to CPU Caching?
In lower level languages, being aware of what gets cached in the CPU can make large differences in performance. Python, being higher level, doesn't give you that kind of control. But that doesn't mean there aren't things you can do.
LUKAS ATKINSON
Learning Intermediate Python With a Deep Dive Course
Do you want to learn deeper concepts in Python? Would the accountability of scheduled group classes help you get past the basics? This week, five Real Python Intermediate Deep Dive workshop members discuss their experiences.
REAL PYTHON podcast
Checking for Membership Using in
and not in
In this video course, you'll learn how to check if a given value is present or absent in a collection of values using Python's in and not in operators, respectively. This type of check is known as membership test in Python.
REAL PYTHON course
How to Strip Characters From a Python String
Use Python's .strip()
method to remove unwanted whitespace or specific characters. Learn about common pitfalls, real-world use cases, and compare .strip()
with similar methods like .lstrip()
and .removesuffix()
.
REAL PYTHON
Django: What's New in 5.2
Django 5.2 was recently released and this post talks about the new features. They include: automatic model imports in the shell, composite primary keys, form customization, the simple block tag, and more.
ADAM JOHNSON
The Best Programmers I Know
In this opinion piece, Matthias writes about the traits he thinks make a good developer. They include things like reading the docs, knowing your tools, continuous learning, helping others, and more.
MATTHIAS ENDLER
BeeWare and the State of Python on Mobile
Talk Python interviews Russell Keith-Magee and they talk about Beeware, a project working towards true native apps built on Python, especially for iOS and Android.
TALK PYTHON
Projects & Code
Nallely: Maps Your MIDI Devices With Anything
GITHUB.COM/DR-SCHLANGE • Shared by vince
Events
Weekly Real Python Office Hours Q&A (Virtual)
April 16, 2025
REALPYTHON.COM
PyData Bristol Meetup
April 17, 2025
MEETUP.COM
PyLadies Dublin
April 17, 2025
PYLADIES.COM
Chattanooga Python User Group
April 18 to April 19, 2025
MEETUP.COM
PyDelhi User Group Meetup
April 19, 2025
MEETUP.COM
PyCon DE & PyData 2025
April 23 to April 26, 2025
PYCON.DE
DjangoCon Europe 2025
April 23 to April 28, 2025
DJANGOCON.EU
PyCon Lithuania 2025
April 23 to April 26, 2025
PYCON.LT
Happy Pythoning!
This was PyCoder's Weekly Issue #677.
View in Browser »
[ Subscribe to 🐍 PyCoder's Weekly 💌 - Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]
15 Apr 2025 7:30pm GMT
Real Python: Creating a Python Dice Roll Application
In this video course, you'll learn how to create a Python dice roll simulator. The course guides you through building a text-based user interface (TUI) application that simulates rolling dice using Python's random
module. You'll learn to gather and validate user input, use random.randint()
for dice rolling, and display results with ASCII art.
By the end of this video course, you'll understand that:
- To simulate dice-rolling events, you can use
random.randint()
. - To get the user's input, you use the built-in
input()
function. - To display dice in Python, you generate ASCII art representations of dice faces and use
print()
. - To manipulate strings, you use methods such as
.center()
and.join()
.
[ Improve Your Python With 🐍 Python Tricks 💌 - Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
15 Apr 2025 2:00pm GMT
PyCon: What to expect at PyCon US sprints
The conference starts days before the first official talk. There's topic-specific summits, sponsor presentations, and deep-dive tutorials that are definitely worth checking out. Similarly, the conference does not end with the last talk. For the next four days, groups of enthusiasts rally around their projects and sprint on making them better in person. Some say it's the best part of the conference, actually. Let's take a closer look then!
Who organizes the sprints?
Sprints at PyCon US are organized by the attendees. The conference provides the space with tables, power strips, Internet connectivity, and, for the first two days, catered lunches. The attendees band together to work on their open-source and community projects of choice.
You can expect bigger projects like CPython, Django, Flask, or BeeWare, to have their own dedicated rooms to hack on their stuff. Smaller projects either group together topically or just join a random friendly room with empty seats.
Of course, the general rules around health and safety apply to the sprints as well. Same goes for the code of conduct. PyCon US staff is still around during sprints, so you can talk to them or to the Sprints chairs, Tania Allard and Cheuk Ting Ho, if you need any help.
Who comes to sprints? Do I need to come for 4 days?
You'll find project maintainers, seasoned contributors, community organizers, and first-time contributors alike. Everybody's welcome!
Most don't stay for all four days, so understandably, everybody wants to maximize what they get out of the experience. So come prepared. Especially if you're only coming for a single day. Our recommendation would be to stay for at least two, this gives it enough time to set everything up and actually create a pull request with a bugfix or feature.
But if you can only spare one day, that's fine, too. Let's cover some ways in which you can make your experience the best.
Which project should I join for sprints?
This is a question worth answering before coming. Sprints work best for contributors who are already users of a given project. If you know a project like, say, CPython or Django well enough, you probably stumbled upon a bug in that software in the past. Maybe you looked into how some internals of that software work. Maybe you thought about making a change to it in the past. Or maybe you at least saw enough tracebacks that you feel somewhat familiar with the software you're using.
The most impactful way to participate in sprints is to choose a project you're familiar with, at least as a user. The project maintainers who come to sprints are helpful people and want you to succeed with your contribution. Meet them halfway and choose a project you already use. There's not enough time during the sprints for maintainers to install software for the first time and explain how it works on somebody else's laptop.
Of course, there's going to be exceptions to every rule. If you first learned about some library or framework at the conference and you're very excited to get involved, by all means join the sprint for that project!
First PR to CPython
For CPython in particular, the maintainers at the sprint recommend that sprint attendees have at least 2 years of experience as users of the Python programming language. A sprint isn't the best place to learn the basics of programming. But it's totally okay to be new at contributing to Python. In fact, this year we'll be trying something new: a dedicated space for first-time contributors to CPython to make sure the experts around you are best-equipped to help you get your first pull request merged. Look for the dedicated "First PR to CPython" signage on the sprint room list.
Are there any easy issues to work on?
This depends on the project. Some issue trackers contain issues marked as "easy" or "help wanted". You can look at those first. Sometimes such issues are a bit of a trap. When an "easy" issue is still open 3+ years later, it often means there's something not particularly easy about it.
Asking the maintainers present at the sprint for an issue to fix is another way to get something to work on. That will often mean that you'll get involved with whatever that maintainer already planned to work on. This might be super interesting or pretty boring to you, depending on what that particular topic area is.
So the best way to find an issue to work on is to scratch your own itch. Fix that bug you also stumbled upon. Add this thing you once wished a library had. Open the list of issues in a library you used last week. Maybe you'll be able to reproduce a problem, add a test, and fix it.
In fact, a related cool way to get involved is to have a laptop with an environment that the maintainer usually doesn't work with. If you see issues on the tracker that need reproducing on Windows or macOS or FreeBSD and this just happens to be the platform that you're on right now, that's perfect!
Speak up!
Sprints are different from tutorials and talks. Everybody, including the experts in the room, hunker down and work on something. If you get stuck with an issue, others around you will probably not notice. A good rule of thumb is to fight with an issue for 45 minutes, and if you're not making progress, let others know where you're stuck. They might be able to help unblock you.
Some maintainers will suggest pair programming, or will be open to the idea if you suggest it. So that's a thing you can try as well if you're both interested in solving a particular problem.
Sometimes two newcomers band together to work on a single issue. This can also be a good strategy and it's more fun to attack a problem with another person interested in solving it.
Preparing your work environment
While the conference is ready for even a large cohort of sprinters to all access wifi at the same time during sprints, it's best to avoid the network congestion on the first day when a lot of people first "git clone" their projects.
If you know the project you want to contribute to, clone their repository before coming. Try to build it and run tests. Even if they're failing for you, you are already way ahead.
If you don't have a project chosen yet, you can still prepare a few things in advance. Install and configure your text editor of choice, and if you already have one, run a round of updates before coming. If you're using any system-wide package manager like Apt or Homebrew, updating your installed packages before coming is a good idea.
Keep in mind that you will be working with other people. If you have a privacy screen on your laptop, it might be helpful to get rid of it for the time of the sprint. Or bring a different device. If you keep your terminal font size tiny to fit a ton of information on screen, you might want to figure out how to increase that font temporarily at least for the sprints so people you collaborate with can see what's going on. This also applies to text editors and their color schemes. Think about your display brightness.
Similarly, if your keyboard layout is esoteric, it will make it harder for others to type on your laptop if you need help. Maybe you can find a quick way to toggle between layouts to allow others to write stuff.
Stay safe
The following section might sound a bit scary, but we're sharing it as common-sense advice for any large gathering of industry professionals where technology is widely actively used. Don't let it deter you from coming!
First things first. Backup your system before coming to the event. You might drop it, you might spill liquid on it, you might leave it at a restaurant or issue just the wrong command on the terminal in the heat of the moment and lose your data. They are all unlikely events, but they all happen at conferences. Backup your system.
This is a large event. People are generally nice and helpful. But if you leave your laptop or phone unattended, somebody might take it, deliberately or not. If you do decide to leave your hardware at the table, put some unique stickers on it, so people don't mistake it for their own. This is especially effective when it comes to smaller accessories like laptop chargers. If you're in need for stickers, you'll find lots of them in the expo hall during the conference!
Finally, don't get hacked. You will be active on a conference-wide network. Keep your system up-to-date, don't bring laptops with legacy operating systems that are no longer receiving security updates. Unless you know and trust the person you're interacting with, be vigilant about system-wide software they want you to install and settings they want you to change. Don't allow strangers to connect devices to your laptop or phone, whether they're thumb drives, keyboards, slide clickers, USB-C chargers, or anything else.
Have fun!
If everything above sounds like a lot, it's only because it's a list of tips gained through 15 years of experience attending sprints at programming conferences. It's there to allow you to prepare, but don't overthink it! Join us, you might really love it.
Sprints are fun, surprisingly productive, and sometimes spark big things! We also can't overstate the importance of putting a face to a name. "Don't be a stranger" is good advice. Connecting a GitHub account name with a good experience you had at a conference is a great way to build trust and fast-track online collaboration in the future!
And that's that. The mysterious sprints demystified! Come and see for yourself whether they're really the best part of PyCon US.
Guest post by Łukasz Langa
15 Apr 2025 9:51am GMT
PyPodcats: Episode 8: With Mojdeh Rastgoo
Learn about Mojdeh's journey. Since discovering Python and open source community in 2016, Mojdeh has been actively contributing to the community and striving for diversity and inclusion by pariticapting in DEI, CoC communities and co-organzing meetupsLearn about Mojdeh's journey. Since discovering Python and open source community in 2016, Mojdeh has been actively contributing to the community and striving for diversity and inclusion by pariticapting in DEI, CoC communities and co-organzing meetups
We interviewed Mojdeh Rastgoo, the newest member of PyPodcats!
Since discovering Python and the open-source community, Mojdeh has been actively involved in the Python ecosystem. She gave her first tutorial in 2018 at EuroSciPy and has since contributed in many ways. She is a member of the PSF Code of Conduct Working Group, a co-organizer of PyLadies Paris, and now a host of PyPodcats!
In this episode, Mojdeh shares more about herself and her passion for the community. We also take a look back at 2024, discuss our plans for 2025, and introduce a few new changes, including our Open Collective account, where you can support us.
Be sure to listen to the episode to hear about our plans and get to know your new host Mojdeh!
Topic discussed
- Introductions
- What are we up to nowadays
- Getting to know Mojdeh
- What Saint-Gobain does and Mojdeh roles in Saint-Gobain
- How did she ended up in Europe
- Her involvement in the community
- PyLadies Paris
- Public speaking and Lightning talks
- Roles of LLM in today's life
- Personal projects
- Growth mindset and changing perspectives
- Personal interests and hobbies
- PyPodcats reflections and plans for the future
- Founding and supports
Links from the show
- PyPodcats Kickstart 2025
- PyPodcats OpenCollective
- Erasmus+ - Erasmus Mundus Master Program
- Think again by Adam Grant
- PyPodcats episode 1 with Joanna Jablonski
- PyPodcats episode 3 with Vicky Twomey-Lee
- PyPodcats episode 4 with Jessica Tegner
Links for PyLadies Paris
15 Apr 2025 9:00am GMT
14 Apr 2025
Planet Python
Django Weblog: DSF member of the month - Öykü Gümüş
For April 2025, we welcome Öykü Gümüş as our DSF member of the month! ⭐
Öykü Gümüş has been Django developer for many years. She has been DjangoCon Europe organizer in 2018 and Django Girls mentor in Istanbul for multiple years. She has been a DSF member since November 2019.
You can learn more about Öykü by visiting Öykü's GitHub Profile.
Let's spend some time getting to know Öykü better!
Can you tell us a little about yourself (hobbies, education, etc)
Hi, I am Öykü, software engineer currently based in Germany.
I studied Computer Engineering in Istanbul, and during my university years, I realised I really enjoy being part of tech communities such as Django Girls, PyLadies and etc.. And I have been trying to play an active role in such groups ever since! Apart from that, I like drawing, and currently trying to improve my illustration skills. In general, I enjoy learning new things. For example started learning cello after 25 years of age, and loving every minute of my attempts to play it. I also love cycling and hiking. Germany is offering so much in those areas and I am always looking for a chance to get on the road.
How did you start using Django?
During my university studies, I started working as a part time developer and my first ever job was with Django. Loved how versatile it was!
What other framework do you know and if there is anything you would like to have in Django if you had magical powers?
Besides Django, I've used Flask, which gives you more control and is great for microservices, and FastAPI, which I really like for its async capabilities and performance. If I had magical powers to add something to Django, I'd probably improve its async support to make it more seamless throughout the stack. Right now, you can work around it, but it's not as smooth as in FastAPI, for example.
What projects are you working on now?
Lately, I've been diving into GraphQL-experimenting with Graphene in Django and playing around with Apollo Client on the frontend. It's been interesting to compare it with traditional REST APIs and explore how it can streamline data fetching in more complex UIs.
Which Django libraries are your favorite (core or 3rd party)?
There are a few Django libraries I keep reaching for, both core and third-party. Core-wise, I really appreciate how solid the django.contrib.admin is. It saves so much time in early development. Also, Django's ORM and authentication system are very well designed-I rarely need to look elsewhere unless I'm doing something super custom. For third-party libraries, a few that I really enjoy using: django-rest-framework django-allauth and graphene-django
What are the top three things in Django that you like?
The ORM, the "Batteries Included" policy and Django's amazing community ❤️
You have been mentor for DjangoGirls+ multiple times, how did you start to mentor? Do you have any recommendation for potential folks interested to mentor?
Oh yes, I met with Django Girls in Istanbul and immediately wanted to take part by mentoring and couldn't love it more! It has great atmosphere and provides such a supportive environment, that I can safely suggest everyone just at least try it once. It's amazing to see the direct impact you can make on people by simply being there. One thing anyone interested in mentoring should never forget is to always maintain an inclusive and safe space.
You were part of the DjangoCon Europe organization in 2018, what makes you volunteer for this event?
The kindness of the organisers of another conference actually. It was Europython 2017 folks, and they kindly provided me, student at the time, a financial aid to join the conference and it was my first tech conference ever! Loved it so much, that I thought I should pay it forward. 🙂
Is there anything else you'd like to say?
Thanks so much for the chat-really enjoyed it! I also just want to say how valuable communities like this are, especially for folks starting out or navigating their path. Having spaces where people can share, support, and learn from each other makes a huge difference.
Thank you for doing the interview, Öykü !
14 Apr 2025 9:10pm GMT
Real Python: Namespaces in Python
A Python namespace is a mapping from names to objects. It works like a dictionary where keys are object names and values are the objects themselves. Namespaces organize variables and functions in a dedicated space, allowing you to use multiple instances of the same name without conflict, as long as they're in different namespaces.
In this tutorial, you'll explore the different types of namespaces in Python, including the built-in, global, local, and enclosing namespaces. You'll also learn how they define the scope of names and influence name resolution in Python programs.
By the end of this tutorial, you'll understand that:
- Python namespaces serve as containers that map names to objects, allowing for organized access and management of variables, functions, classes, and objects in general.
- Namespace and scope differ in that a namespace maps names to objects, while a scope is the region of code where you can access a name.
- Python implements most namespaces using dictionaries, where each namespace's lifecycle is tied to the execution context, such as global or local scopes.
Understanding how namespaces work will improve your ability to manage and organize code efficiently in Python programs, helping to prevent name conflicts and other issues. To get the most out of this tutorial, you should be familiar with Python variables and functions. Knowledge of inner functions and closures will also be a plus.
Get Your Code: Click here to download the free sample code that you'll use to learn about namespaces and scope in Python.
Take the Quiz: Test your knowledge with our interactive "Namespaces in Python" quiz. You'll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Namespaces in PythonIn this quiz, you'll test your understanding of Python namespaces. These concepts are crucial for organizing the symbolic names assigned to objects in a Python program and ensuring they don't interfere with one another.
Getting to Know Namespaces in Python
A namespace is a container that holds the currently defined symbolic names and the objects each name references. You can think of a namespace as a dictionary, in which the keys are object names and the values are the objects themselves. Each key-value pair maps a name to its corresponding object.
Namespaces let you use the same name in different contexts without collisions. It's like giving everything its own little room in a well-organized house. They allow Python to keep things organized, prevent naming conflicts, support the concept of scope, and enforce modularity.
Namespaces are so crucial in Python that they were immortalized in The Zen of Python:
Namespaces are one honking great idea-let's do more of those!
- Tim Peters
As Tim Peters suggests, namespaces aren't just great. They're honking great, and Python uses them extensively. Depending on how you structure your code, a Python program can have up to four different types of namespaces:
- Built-In
- Global
- Local
- Enclosing or nonlocal
These namespaces have differing lifetimes. As Python executes a program, it creates namespaces as necessary and removes them when it no longer needs them. Typically, many namespaces will exist at any given time.
The Python global, local, and nonlocal namespaces are implemented as dictionaries. In contrast, the built-in namespace isn't a dictionary but a module called builtins
. This module acts as the container for the built-in namespace.
In the following sections, you'll learn about these four namespaces and what their content and behavior are.
The Built-in Namespace
The built-in namespace contains the names of all of Python's built-in objects. This namespace is available while the Python interpreter is running. So, you can access the names that live in this namespace at any time in your code without explicitly importing them.
You can list the objects in the built-in namespace with the dir()
function using the __builtins__
object as an argument:
>>> dir(__builtins__)
[
'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
...
'super',
'tuple',
'type',
'vars',
'zip'
]
You may recognize some objects here, such as built-in exceptions, built-in functions, and built-in data types. Python creates the built-in namespace when it starts and keeps it active until the interpreter terminates.
The Global Namespace
The global namespace contains the names defined at the module level. Python creates a main global namespace when the main program's body starts. This namespace remains in existence until the interpreter terminates.
Additionally, each module has its own global namespace. The interpreter creates a global namespace for any module that your program loads with the import
statement. For further reading on main functions and modules in Python, see the following resources:
Read the full article at https://realpython.com/python-namespace/ »
[ Improve Your Python With 🐍 Python Tricks 💌 - Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
14 Apr 2025 2:00pm GMT
Real Python: Quiz: Namespaces in Python
In this quiz, you'll test your understanding of Namespaces in Python.
You'll revisit how Python organizes symbolic names and objects in namespaces, when Python creates a new namespace, how namespaces are implemented, and how variable scope determines symbolic name visibility.
[ Improve Your Python With 🐍 Python Tricks 💌 - Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
14 Apr 2025 12:00pm GMT