How to fix issues with E402?

本小妞迷上赌 提交于 2019-12-02 04:02:06

问题


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?


回答1:


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."



来源:https://stackoverflow.com/questions/48498139/how-to-fix-issues-with-e402

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!