user7692855
user7692855

Reputation: 1420

Python import in Init

I am writing a lot of tests at the moment that all use pytest. So the first time of every file is import pytest. Is there a way to import it somewhere else for example the __init__.py

tests
   - unit_tests
       - __init__.py
       - test_service.py
       - test_plan.py
       - test_api.py

Upvotes: 0

Views: 30

Answers (1)

chepner
chepner

Reputation: 531035

An import statement has two purposes:

  1. Define a module, if necessary
  2. Add a name for that module in the current scope.

While putting import pytest in __init__.py would take care of the first one, it does nothing for the second. You have no way of using pytest in each module unless you import sys and use sys.modules['pytest'] everywhere you would have used pytest alone. But that's ugly, so you might think, "Hey, I'll just write

pytest = sys.modules['pytest']

to make a global name pytest refer to the module."

But that's exactly what import pytest already does.

Upvotes: 2

Related Questions