[Python]“from modulename import *” in Python2 and Python3

Background

from modulename import *
modulename
├── __init__.py
└── modulename.so
from modulename import *
ClsPublic = ClsPersonal # export it as ClsPublic

Solution

import modulename
print(modulename) # Leading different results.
  1. Python 2 supports implicit relative imports. Python 3 does not.
  2. Python 2 requires __init__.py files inside a folder in order for the folder to be considered a package and made importable. In Python 3.3 and above, thanks to its support of implicit namespace packages, all folders are packages regardless of the presence of a __init__.py file.
  3. In Python 2, one could write from <module> import * within a function. In Python 3, the from <module> import * syntax is only allowed at the module level, no longer inside functions.
  1. using six
import six
if six.PY2:
from modulename import *
else:
from modulename.modulename import *
import .modulename import *

--

--

--

From Taiwan, a beautiful island. Learning English and sharing code experience.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Singly linked list in GoLang

Hiding from Delve in Office 365

Sharpen the competitive edge of your IT: move your code to containers

An Introduction to AWS

Join multiple .avi files in Ubuntu

Why People Should Learn To Program

The Hardest Parts of My Job as a Software Engineer

UML: Activity Diagram

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jaime Lin

Jaime Lin

From Taiwan, a beautiful island. Learning English and sharing code experience.

More from Medium

Python Static Arrays, Dynamic Arrays, and Deques

Interview Tips: How to use Lists efficiently in Python

Implementing a Heap in Python

[LeetCode] 461. Hamming Distance