简体   繁体   English

常量类实例是PEP8命名约定的例外吗?

[英]Are constant class instances an exception to PEP8 naming convention?

If I declare an instance at the module level, which is to be set once and never changed, should I stick to uppercase naming conventions from PEP8? 如果我在模块级别声明一个实例,该实例将被设置一次且永不更改,那么我应该坚持使用PEP8的大写命名约定吗?

Eg 例如

entity_manager = EntityManager(config)

vs VS

ENTITY_MANAGER = EntityManager(config)

There is usually no discussion when the constant is a primitive type, eg an integer. 当常量是原始类型(例如整数)时,通常不会进行讨论。 But what about this? 但是呢?

The general spirit of PEP8 is to "Keep your code consistent", whether that constant is int, string, or class instance. PEP8的基本精神是“保持代码一致”,无论该常量是int,字符串还是类实例。

According to PEP8, use upper case letters separated by underscore for constants that won't be changed through out your code. 根据PEP8,请使用下划线分隔的大写字母表示不会在您的代码中更改的常量。 That coupled with consistency , should be applied all throughout your constants, including class instances. 再加上一致性 ,应该应用于所有常量,包括类实例。

On using UpperCase letters : 关于使用大写字母

Constants are usually defined on a module level and written in all capital letters with underscores separating words. 常量通常在模块级别定义,并以所有大写字母书写,并用下划线分隔单词。 Examples include MAX_OVERFLOW and TOTAL. 示例包括MAX_OVERFLOW和TOTAL。

I agree with the general spirit of PEP8 and to keeping your code consistent. 我同意PEP8的总体精神并保持您的代码一致。 If there are issues you have with PEP8, update your .pylintrc after reaching a consensus with your team. 如果您在PEP8方面遇到问题,请在与团队达成共识后更新.pylintrc。

Regarding the original post, I also agree with the uppercase declarations of "constants," regardless of them being primitives or objects. 关于原始帖子,我也同意“常量”的大写声明,无论它们是基元还是对象。 What I disagree with, and this goes against convention, is the use of all uppercase at the module level for everything that may be immutable. 我不同意的是,这违背了惯例,就是在模块级别对所有可能不变的东西使用所有大写字母。 Since Python does not enforce this directly, it's up to us to define naming conventions that imply both purpose and scope for developers picking up where you left off. 由于Python不会直接强制执行此操作,因此我们需要定义命名约定,这些约定隐含了开发人员从您离开的地方开始的目的和范围。 If I don't want my "constant" to be accessible from another module, there's not much I can do in Python other than prefix with an underscore, make lowercase, or obfuscate the name in some way. 如果我不希望从另一个模块访问“常量”,那么除了用下划线前缀,小写字母或以某种方式混淆名称之外,在Python中我无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM