Mihai Neacsu
Mihai Neacsu

Reputation: 2095

Should __init__.py also contain python module imports?

When writing your own package in Python, should __init__.py contain imports like os, sys? Or should these just be imported within the file that is using them?

Upvotes: 2

Views: 285

Answers (1)

unutbu
unutbu

Reputation: 879481

Import the modules in the module that uses them.

Placing import os in __init__.py would put os in the package's global namespace, but it would not affect the namespace of the module that uses os. Global namespaces are not shared across modules or packages, so you would get NameErrors if you did not import them in the module that uses os.

Upvotes: 3

Related Questions