1

I have a lint error "Module level import not at top of file" which I'm not sure how to treat corretly and in the most elegant manner.

I have a python module which I want to test. This module can run in simulation mode or real mode, the mode is set in an environment variable.

It initializes a module-scoped variable depending on the env variable flag.

from util.config import ENV_SIMULATION_MODE

def method_1():
   # do something with _my_instance

class Real(base):
   ...
class Simulation(base):
   ...

_my_instance = simulation() if ENV_SIMULATION_MODE else real() 
...

Now I want to test this module, say method_1. I wouldn't like to to set ENV_SIMULATION_MODE variables to the unit test process itself, because i might want to test both modes, and also I want to allow the developers to run unit tests without having to set this setting.

I Want to set them before running the test logic, like so:

from util import config
config.ENV_SIMULATION_MODE = False

from my_module import method_1

class WeatherTestCase(unittest.IsolatedAsyncioTestCase):
   def test_method1():
      # test method_1

But I get a linter error - E402 module level import not at top of file - Indeed I import method_1 only after doing some logic.

I see 2 options, and I don't really like either of them:

  1. Move the initialization of _my_instance code to an initialize() method - i don't like having to change API of code for unittest, least of all for linting purposes
  2. Disable this check in the lint configuration for test files - not ideal

I think this case should be fairly common, what is the most elegant way out of this?

Yossi Vainshtein
  • 3,845
  • 4
  • 23
  • 39
  • Just add `# NOQA` at the end of the `import` line that is causing the error. This tells the linter to skip that particular line. – larsks Feb 09 '21 at 19:02

0 Answers0