如何解决E402的问题? [英] How to fix issues with E402?

查看:981
本文介绍了如何解决E402的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试解决PEP8 E402的问题.

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?

推荐答案

PEP8中指定的准则仅是-准则.当它们有意义时,它们是一组要遵循的规则.

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

E402表示导入仅位于文件的顶部.这是为了停止以下操作:

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

在上面的示例中,很难知道math是否已导入.如果您需要在文件末尾再次使用math,而没有E402通知您,您可能会再次使用import math,这是无害的,但是草率.

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.

就您而言,您并不草率.在导入另一个库之前,您要专门设置一些东西,或者向用户提供更好的错误消息.只需告诉您的linter忽略注释中建议的那些行上的警告,并在行的末尾添加# noqa: E402即可.当您告诉小孩子我知道我在做什么,走开."时,您可以想到这一点.

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

这篇关于如何解决E402的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆