忽略 flake8 检查带有反斜杠的代码

Ignore flake8 check for the code with backslash

有没有办法用 \ 忽略 flake8 检查部分代码?我无法在 \ 之后添加 #noqa

例如,这是我的代码。 .config('spark.driver.maxResultSize', os.getenv('spark_driver_max_result_size')) \ 超过 79 个字符

session = SparkSession \
    .builder \
    .appName(os.getenv('app_name')) \
    .config('spark.yarn.queue', os.getenv('spark_yarn_queue')) \
    .config('spark.driver.memory', os.getenv('spark_driver_memory')) \
    .config('spark.executor.memory', os.getenv('spark_executor_memory')) \
    .config('spark.driver.maxResultSize', os.getenv('spark_driver_max_result_size')) \
    .enableHiveSupport() \
    .getOrCreate()

这行不通。

session = SparkSession \
    .builder \
    .appName(os.getenv('app_name')) \
    .config('spark.yarn.queue', os.getenv('spark_yarn_queue')) \
    .config('spark.driver.memory', os.getenv('spark_driver_memory')) \
    .config('spark.executor.memory', os.getenv('spark_executor_memory')) \
    .config('spark.driver.maxResultSize', os.getenv('spark_driver_max_result_size')) \  # noqa: E501
    .enableHiveSupport() \
    .getOrCreate()

您可以将表达式括在括号中,然后在这些括号中正常使用换行符

session = (SparkSession 
    .builder 
    .appName(os.getenv('app_name')) 
    .config('spark.yarn.queue', os.getenv('spark_yarn_queue')) 
    .config('spark.driver.memory', os.getenv('spark_driver_memory')) 
    .config('spark.executor.memory', os.getenv('spark_executor_memory')) 
    .config('spark.driver.maxResultSize', os.getenv('spark_driver_max_result_size')) # noqa: E501
    .enableHiveSupport()
    .getOrCreate())

我建议不要试图让 flake 停止抱怨,而是建议用类似的方式打破界限:

session = (SparkSession
    .builder
    .appName(os.getenv('app_name'))
    .config('spark.yarn.queue', os.getenv('spark_yarn_queue'))
    .config('spark.driver.memory', os.getenv('spark_driver_memory'))
    .config('spark.executor.memory', os.getenv('spark_executor_memory'))
    .config('spark.driver.maxResultSize', 
            os.getenv('spark_driver_max_result_size'))
    .enableHiveSupport()
    .getOrCreate()
)

PEP8 says:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable: