Python“ private”函数编码约定

在编写 python 模块和函数时,我有一些“公共”函数应该向外部人员公开,但另一些“私有”函数应该只能在本地和内部看到和使用。

我知道在 python 中没有绝对的私有函数。但是,区分“公共”函数和“私有”函数的最佳、最简洁或最常用的样式是什么呢?

我列举了一些我知道的风格:

  1. 在模块文件中使用 __all__表示其“公共”函数(Python _ _ all _ _ module 级别变量的用途是什么?)
  2. 在“ private”函数的名称开头使用下划线

人们还有什么其他的想法或惯例吗?

非常感谢!

70326 次浏览

From Python's Class module documentation:

Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.