1

PEP8 dictates that you put your imports at the top of your code, which allows the reader to see what you are importing in one space.

However if you have a local repo for functions in order to import them you must first change your current directory.

If you try to change your directory then you get a PEP8 violation because your imports aren't all in one place

import sys
import pandas as pd

sys.path.insert(0, r'local\path')

from local_functions import function_1

I understand that "A Foolish Consistency is the Hobgoblin of Little Minds" and if I have to deal with a PEP8 violation that's okay.

I just imagine there is an actual solution to this as lots of people must be writing functions and importing them.

Is there a way to import locally stored functions that doesn't create a PEP8 violation?

Edit: As noted here: https://stackoverflow.com/a/53832780/9936329

# noinspection PyUnresolvedReferences
from local_functions import function_1  # noqa: E402

Will note that you are intentionally breaking PEP8 and also not inspect for unresolved references.

Violatic
  • 374
  • 2
  • 18

1 Answers1

1

It will depend on the circumstances, but if it is only to satisfy the linter, you could maybe place your import in a try/except block?

import sys
import pandas as pd

try:
    from local_functions import function_1
except ModuleNotFoundError:
    sys.path.insert(0, r'local\path')
    from local_functions import function_1

Alternatively, you could use relative, or absolute imports, giving the location of your module relative to your project folder, or the absolute path on your HD.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • This does satisfy the linter, as you say. But it seems like a workaround rather than "good code" that PEP8 tries to enforce. I think those saying to make a package might be the best option? But again it doesn't feel that clean. – Violatic Jun 10 '19 at 16:14
  • agreed - Alternatively, you could use relative, or absolute imports, giving the location of your module relative to your project folder, or the absolute path on your HD. – Reblochon Masque Jun 10 '19 at 16:18