Changes in import statement python3

Cover Image for Changes in import statement python3
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Changes in Import Statements in Python 3: What You Need to Know! 🐍

Are you scratching your head trying to understand the changes in import statements in Python 3? Don't worry, you're not alone! 🤔

The Python 3 documentation can be a bit overwhelming, so in this blog post, we'll break it down for you in a simple and engaging way. By the end, you'll have a clear understanding of what's changed and how you can adapt your code.

Understanding Relative Imports: What Are They? 🤷‍♀️🤷‍♂️

Before we dive into the changes, let's quickly review what a relative import is. In Python, relative imports are used to import modules and packages relative to the current location of the script you're running.

For example, let's say you have the following directory structure:

my_package/
    __init__.py
    module1.py
    module2.py

If you're in module1.py and you want to import module2.py, you can use a relative import like this:

from . import module2

The dot (.) represents the current package, in this case, my_package. Without the dot, Python would interpret the import statement as an absolute import, searching for module2 in the top-level modules.

Changes in Python 3: Say Goodbye to Implicit Relative Imports! 👋

With the release of Python 3, implicit relative imports within packages are no longer available. You can now only use absolute imports and explicit relative imports. But what does that mean?

  1. Absolute Imports ➡️

An absolute import refers to importing a module, package, or object using its absolute name, starting from the top-level package.

from my_package import module2
  1. Explicit Relative Imports ➡️

Explicit relative imports are used when you want to import a module or package relative to the current location, explicitly indicating the relative path using dots.

from . import module2

By using explicit relative imports, you ensure your code is explicit about the dependencies it relies on and improves code clarity.

Understanding Star Imports: What's the Deal? ✨

Now that we've covered relative imports, let's address your other question about star imports. In Python 2, star imports (e.g., from module import *) were allowed not only at the module level but also within functions, classes, and other scopes.

In Python 3, star imports are only permitted in module-level code. This change was made to improve code readability and avoid polluting the global namespace.

To demonstrate this, let's compare Python 2 and Python 3 code:

# Python 2
def my_func():
    from module import *  # Allowed in Python 2

# Python 3
def my_func():
    from module import *  # Not allowed in Python 3

In Python 3, the star import within the function would raise a SyntaxError. To fix this, you need to import the specific objects you require explicitly, like this:

def my_func():
    from module import object1, object2, object3

This way, you explicitly state which objects you're importing, making your code more readable and preventing potential naming conflicts.

Embrace the Changes: Updating your Python 2 Code 🔄

Updating your code to adhere to the changes in Python 3 may seem daunting, but it's essential to embrace these changes to ensure compatibility and best practices.

To update your code, follow these steps:

  1. Replace any implicit relative imports with explicit relative imports.

  2. Remove star imports from anywhere other than the module-level code.

  3. If necessary, update your import statements to use the absolute path.

By doing so, you'll have code that works seamlessly in both Python 2 and Python 3, and you'll be following the recommended practices!

Conclusion and Call-to-Action: Keep Learning! 🚀

Understanding the changes in import statements in Python 3 is crucial for any developer working with Python. By grasping the differences, you'll be able to write more robust and future-proof code.

Remember to:

  • Use explicit relative imports instead of implicit relative imports.

  • Limit star imports to module-level code to avoid namespace pollution.

  • Update your existing Python 2 code to comply with the changes.

Now it's your turn! Share your thoughts and experiences with the changes in a comment below. Have you encountered any challenges while transitioning from Python 2 to Python 3? Let's discuss and help each other out! 🎉


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello