5 Easy Tips for Switching from Python 2 to 3

Introduction:

In this tutorial, we are learning about 5 easy tips for switching from Python 2 to 3. Many significant Python projects have pledged to transition entirely to Python 3. We can use NumPy, Pandas, SciPy, etc, in data science. TensorFlow, Scikit-Learn, XGBoost, etc., are used in machine learning. For the Web application, we used requests, Tornado. As major libraries fully transition to Python 3, updating your code base becomes essential. In this tutorial, we will explore five simple tips to help you transition from the Python 2 version to the Python 3 version.

1. Imports:

While Python 2 used relative import, Python 3 now uses absolute import to make it more transparent. Consider the following folder structure:

In Python 2, relative imports are written based on the current file's location. For instance, to import some helper code into our theme, we would do the following -

Python 3 no longer supports this style of importing because it does not make clear whether you want the "relative" or "absolute" version of `helper_code`. If a Python package named `helper_code` was installed on your computer, you might accidentally import the wrong one. Now, Python 3 requires explicit imports, where you clearly specify the module's location relative to your current working directory. Therefore, importing your helper code would look like this -

Notice the dot (.) beside the package name, which indicates that the package is in the current directory. Similarly, using two dots (..) before the package name (like ..helper_code) tells Python that the package is one directory above the current location of main_code.py. The key point is that Python 3 requires you to provide the precise location of the package.

2. Print statements:

Many of us have encountered errors related to Python print statements at some point. This is a change that will definitely require anyone using Python 2 print statements to switch to the Python 3 format. We give an example below -

Essentially, you need to add parentheses to all your print statements in your code. Fortunately, once you include the parentheses, the print statements will be compatible with both Python 2 and Python 3.

3. Integer division:

Using the / operator to divide integers would result in the quotient being rounded down to the nearest integer in Python 2. You had to convert the integers to float before performing the division to get a floating-point result. Python 3 simplifies this by introducing two different operators: / for float division and // for integer division. Python 3 simplifies this by introducing two different operators: / for float division and // for integer division.

The use of explicit operators in Python 3 enhances code clarity and readability. The // operator is clearly for integer division, while the / operator is for floating-point division, eliminating the need for explicit type conversions. It is important to note this change because if you do not update your integer division from / to // when transitioning from Python 2 to 3. You might end up with floating-point results instead of integers.

4. Formatting the String:

String formatting syntax is much improved in Python 3. In Python 2, you would use the % sign like this:

There are a few key points about those Python 2 statements:

  1. The types of the variables are explicitly specified like %d for int, %s for string, and %f for float.
  2. The string and variables are written separately and placed side by side.
  3. The style resembles Python 2 print statements, using % signs for inserting variables and not using brackets.

Python 3 introduces a string formatting method found in the string class, using str.format(). This formatter allows you to combine elements within a string using positional formatting.

The new format() function simplifies the process. This function allows you to format strings in a single and clear statement without needing to specify types. Just ensure the variables are in the correct order, and everything will work seamlessly.

5. Returning the iterable objects instead of lists:

In Python 3, many built-in functions return an iterator instead of a list. This change primarily aims to improve memory efficiency, as iterators typically use less memory than lists. When using an iterator, elements are generated and stored in memory only as needed. This allows for the creation of large datasets, such as billions of points, without consuming excessive memory. In contrast, creating a list of 1 billion floating point numbers requires sufficient RAM to store all the data simultaneously. In general, using iterators behaves like lists. An example is looping over the output of the range() function. We give an example of it -

Notice that the syntax remains the same, even though in Python 3, range()returns an iterator. If you specifically need a list, you can easily convert the iterator by using the list()function.

Some commonly used functions and methods in Python 3 that return iterators instead of lists include zip(), map(), filter(), and some dictionary methods like .keys(), .values(), and .items().

Conclusion:

In this tutorial, we'll explore five simple tips to help you transition from the Python 2 version to the Python 3 version. This shift is essential for ensuring compatibility with modern tools and libraries used in data science, machine learning, and web development by following the five easy tips outlined, which are updating import statements, modifying print statements, adjusting integer division operations, using the new string formatting method, and understanding the use of iterators instead of lists. These changes will help improve code readability, efficiency, and compatibility with the latest advancements in Python.