21

We are trying to fix issues with PEP8 E402.

Mostly our code is broken on:

import os
os.environ['LIB_CAN_THROW_ERROR_ON_IMPORT'] = 2
import lib
os.environ['LIB_CAN_THROW_ERROR_ON_IMPORT'] = 0 # back

-

if sys.version_info[0] > 2:
    import python3lib
else:
    import python2lib

-

try:
    import lib
except:
    print('lib is required')
    sys.exit(1)

How to solve these violations?

aleskva
  • 1,644
  • 2
  • 21
  • 40
  • 7
    `# noqa: E402`? – Klaus D. Jan 29 '18 at 09:39
  • 1
    I think your solution will work only for pycodestyle, not for flake8 and still this is an ignored PEP8 violation. The same as adding E402 to tox.ini for flake8, it is not a solution, just workaround – aleskva Jan 29 '18 at 09:46
  • 2
    The most common violation of PEP 8 is IMHO "A Foolish Consistency is the Hobgoblin of Little Minds". – Klaus D. Jan 29 '18 at 09:52
  • I quoted a very important (and often ignored) part of PEP 8 which basically says: it is not smart to apply theses rules at all cost. – Klaus D. Jan 29 '18 at 10:11
  • Sure it is, but I believe at least one of those issues can be solved somehow. That's why I ask experienced community here – aleskva Jan 29 '18 at 10:17
  • Then, you should at least add some explanations to your question: What you are doing, what the exact problem is, what tool you are using and how, what their output is, what you have tried to fox it and why it did not work… – Klaus D. Jan 29 '18 at 10:20
  • 1
    @aleskva Please don't be rude to people trying to help you. :( – Adam Barnes Jan 29 '18 at 12:13

1 Answers1

31

The guidelines specified in PEP8 are just that - guidelines. They're a set of rules to follow when they make sense.

E402 refers to imports only being at the top of a file. This is to stop the following:

import pygame

# 800 lines of pygame stuff
...

import math
# 10 lines of math stuff
...

# Another 800 pygame lines

In the above example, it's very difficult to know that math is imported. If you need to use math again at the end of the file, without E402 telling you off, you'll probably import math again, which is harmless, but sloppy.

In your case, you're not being sloppy. You're specifically setting some things before importing another library, or providing better error messages to users. Simply tell your linter to ignore the warnings on those lines as suggested in the comments, with # noqa: E402 at the end of the line. You can think of this as you telling the linter "I know what I'm doing, go away."

Adam Barnes
  • 2,922
  • 21
  • 27
  • 2
    If you'd like to explain why you downvoted my answer many years after I posted it, then perhaps I can improve it. – Adam Barnes Jun 30 '21 at 02:46