1

I have done some research and learned that python's import statement only imports something once, and when used again, it just checks if it was already imported. I'm working on a bigger project and noticed that the same thing is imported in multiple files, which aparently doesn't affect performance but leaves the code a bit polluted imo. My question is: is there a way to import something only once and use it everywhere in the directory without calling the import statement over and over?

Here are some of the modules that I'm importing in various files:

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import *
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jalkun
  • 219
  • 2
  • 12

1 Answers1

2

Each module (.py file) that needs to have those imported names in scope, will have to have its own import statements. This is the standard convention in Python. However, it's not recommended to import * but rather to import only the names you will actually use from the package.

It is possible to put your package import statements in a __init__.py file in the directory instead of in each .py file, but then you will still need a relative import statement to import those names from your package, as described here: Importing external package once in my module without it being added to the namespace

Alex Kyllo
  • 198
  • 6
  • It's also worth noticing that similar patterns are common in other languages, like the `include` statements for C, PHP, etc. Not only it doesn't actually "pollute" the code, it also allows to make it more tidier. – musicamante Oct 16 '20 at 18:24