Python Forum

Full Version: Import vs from x import
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to figure out why you would create a containing class if you were just going to import it from a file, vs just creating the general classes that you will simply import.

I'm just wondering if the two code examples below are equivilent. If not, what differences would there be?

Using simple "import Creds":

Creds.py:
import random class Server1: url = "server1.com" username = "username" password = "password" randkey = random.randint(1, 10) class Server2: url = "server2.com" username = "username" password = "password" randkey = random.randint(1, 10)
import Creds print(Creds.Server2.randkey)
versus using "from creds import Creds":

creds.py:
import random class Creds: class Server1: url = "server1.com" username = "username" password = "password" randkey = random.randint(1, 10) class Server2: url = "server2.com" username = "username" password = "password" randkey = random.randint(1, 10)
from creds import Creds print(Creds.Server2.randkey)
# Creds.py class Server1: … class Server2: …
Here, Creds is a module whose attributes happen to be two classes. You do
import Creds print(Creds.Server2.randkey)
Modules are singletons in sys.modules,they have their own namespace,and you can add functions, variables, etc. at the same level as Server1/Server2.

Nested classes inside a container class
# creds.py class Creds: class Server1: … class Server2: …
Here, creds is still a module, but the only top-level symbol you expose is the Creds class. You do
from creds import Creds print(Creds.Server2.randkey)
It’s more common in Python to use modules as namespaces.
If you need to break things out further, you’d typically make creds/ a package with __init__.py or separate sub-modules (creds/server1.py, etc.),
rather than nest classes which just add a level of confusing.
Nested classes are often reserved for cases where the inner class is really an implementation detail of the outer class (e.g. helper types), not just for grouping constants.

Tools (IDEs, linters, documentation generators) expect modules to contain top-level classes and functions.
Nesting can sometimes confuse auto-completion or doc-builders or people who try to read the code.

Unless you have a compelling reason to nest classes,
stick with the module-level approach (or split into sub-modules) for clarity, simplicity,and compatibility with the wider Python ecosystem.