- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
TL;博士:将实现细节排除在模块命名空间之外的最简洁方法是什么?
已经有许多关于这个主题的类似问题,但相对于现代工具和语言特性,似乎没有一个有令人满意的答案。
我正在设计一个 Python 包,我想保持每个模块的公共(public)接口(interface)干净,只公开预期的内容,隐藏实现细节(尤其是导入)。
多年来,我看到了许多技术:
别担心。只需记录如何使用您的包,让其消费者忽略实现细节。
在我看来,这太可怕了。一个设计良好的界面应该很容易被发现。公开可见的实现细节会使界面更加困惑。即使作为包的作者,我也不想在它暴露太多时使用它,因为它会使自动完成功能变得不那么有用。
在所有实现细节的开头添加下划线。
这是一个很好理解的约定,大多数开发工具都足够智能,至少可以将下划线前缀的名称排序到自动完成列表的底部。如果你有少量的名字来这样处理它工作得很好,但是随着名字的数量增加,它变得越来越乏味和丑陋。
以这个相对简单的导入列表为例:
import struct
from abc import abstractmethod, ABC
from enum import Enum
from typing import BinaryIO, Dict, Iterator, List, Optional, Type, Union
import struct as _struct
from abc import abstractmethod as _abstractmethod, ABC as _ABC
from enum import Enum as _Enum
from typing import (
BinaryIO as _BinaryIO,
Dict as _Dict,
Iterator as _Iterator,
List as _List,
Optional as _Optional,
Type as _Type,
Union as _Union
)
from
可以部分缓解这个问题。进口,只进口整个包,和包限定一切。虽然这确实有助于这种情况,而且我意识到有些人无论如何都喜欢这样做,但这并不能消除问题,这不是我的偏好。有些包我更喜欢直接导入,但我通常更喜欢显式导入类型名称和装饰器,以便我可以不加限定地使用它们。
class Widget(_ABC):
@_abstractmethod
def implement_me(self, input: _List[int]) -> _Dict[str, object]:
...
Widget
执行会看到他需要执行
implement_me
方法,需要取一个
_List
并返回
_Dict
.这些不是实际的类型名称,现在实现隐藏机制已经泄露到我的公共(public)接口(interface)中。这不是一个大问题,但它确实导致了这个解决方案的丑陋。
def module():
import struct
from abc import abstractmethod, ABC
from typing import BinaryIO, Dict, List
def fill_list(r: BinaryIO, count: int, lst: List[int]) -> None:
while count > 16:
lst.extend(struct.unpack("<16i", r.read(16 * 4)))
count -= 16
while count > 4:
lst.extend(struct.unpack("<4i", r.read(4 * 4)))
count -= 4
for _ in range(count):
lst.append(struct.unpack("<i", r.read(4))[0])
def parse_ints(r: BinaryIO) -> List[int]:
count = struct.unpack("<i", r.read(4))[0]
rtn: List[int] = []
fill_list(r, count, rtn)
return rtn
class Widget(ABC):
@abstractmethod
def implement_me(self, input: List[int]) -> Dict[str, object]:
...
return (parse_ints, Widget)
parse_ints, Widget = module()
del module
ptpython
例如,无法为
parse_ints
提供方法签名信息功能。还有
Widget
的类型变成
my_package.module.<locals>.Widget
而不是
my_package.Widget
,这让消费者感到奇怪和困惑。
__all__
.
__all__
中的“公共(public)”成员。多变的:
import struct
from abc import abstractmethod, ABC
from typing import BinaryIO, Dict, List
__all__ = ["parse_ints", "Widget"]
def fill_list(r: BinaryIO, count: int, lst: List[int]) -> None:
... # You've seen this.
def parse_ints(r: BinaryIO) -> List[int]:
... # This, too.
class Widget(ABC):
... # And this.
__all__
影响是使用通配符导入时会发生什么
from my_package import *
,无论如何,大多数人都不会这样做。
__init__.py
中公开公共(public)接口(interface).
my_package/
+--__init__.py
+--_widget.py
+--shapes/
+--__init__.py
+--circle/
| +--__init__.py
| +--_circle.py
+--square/
| +--__init__.py
| +--_square.py
+--triangle/
+--__init__.py
+--_triangle.py
__init__.py
文件看起来像这样:
# my_package.__init__.py
from my_package._widget.py import parse_ints, Widget
# my_package.shapes.circle.__init__.py
from my_package.shapes.circle._circle.py import Circle, Sphere
# my_package.shapes.square.__init__.py
from my_package.shapes.square._square.py import Square, Cube
# my_package.shapes.triangle.__init__.py
from my_package.shapes.triangle._triangle.py import Triangle, Pyramid
最佳答案
转换为子包以限制一个地方的类数量并分离关注点。
如果在其模块之外不需要类或常量,请在其前面加上双下划线。如果您不想从中显式导入许多类,请导入模块名称。
你已经列出了所有的解决方案。
关于python - 避免 Python 中的模块命名空间污染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728884/
我面临以下问题: 我有一个命名空间 Exception\* , 其中包含多种类型 异常(exception)。 我有一个命名空间 Exception\User\* ,其中包含一个 特定类型的异常 (
新的 Highcharts v3.0 气泡图看起来很棒。是否可以用名称/一些文本注释和显示每个气泡? 谢谢,奈杰尔。 最佳答案 您需要做两件事。 首先,命名每个数据点(气泡): data: [ {
我通过使用 EVP_get_cipherbyname("AES-256-CTR") 获得了 EVP_CIPHER*,现在我想找到一种方法从 EVP_CIPHER* 返回到原始名称,在本例中为“AES-
为了避免 JavaScript 堆问题,我使用多个数组:family1、family2、family3 ...、dogs1、dogs2、dogs3 ... 使用示例:“family1 和 dogs1”
我很难理解这段代码。这不是我熟悉的典型 Javascript 函数语法。这是一个命名函数吗?或者这是更新事件的回调?抱歉,我对新手问题很陌生,我对 JS 还很陌生。我了解正在发生的一切,除了这个函数语
是否可以在 python 中执行以下操作? i=1 while True: w = open("POSCAR_i","w") i=i+1 if i<10:
我问这个是因为我刚刚在一段代码上看到它: var myVar = function func(arg){ console.log(arg); } 我不明白为什么函数在为 myVar 定义之前被“
我正在尝试为 ActiveDirectory 创建上下文(客户端和服务器都是 Windows),使用我的 Windows 凭据和 NTLM。 这是我的代码: public void func() {
我正在运行一个使用 JBoss5 容器的 ejb 示例。我正在使用一个例子 from here(Part one) . 在示例中,我在 JBoss 中部署了 bean,在 Tomcat 中部署了一个应
我希望能够命名一个 BackgroundWorker 以便于调试。这可能吗? 最佳答案 我必须尝试,但你不能只设置 Name BackgroundWorker 执行的 DoWork() 方法中的线程?
我在 Android Activity 和其他类之间遇到了越来越多的命名冲突。我想知道你能不能告诉我你是如何避免这些的。遗憾的是,关于 SO 的相关问题并未涵盖我的特定命名问题。 第一个例子 我有一个
当我尝试使用 loadChildren 加载模块以在命名 socket 中加载模块的组件时,出现抛出错误。 有没有办法在命名的路由器 socket 中延迟加载模块? //html //routing
很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .
在 Type Driven Development with Idris 第 6 章的代码中,我对这段代码感到困惑: data DataStore : Type -> Type where M
通常,如果有一个属性可以获取/设置状态值,我会使用“Is”,例如: Visibility: .IsVisible 但是对于获取/设置操作的属性,最好使用什么?喜欢: Casting shadows:
好的,所以如果你可以很容易地想到一个名词,那么命名一个接口(interface)(或类)很容易:用户、窗口、数据库、流等。 形容词或形容词的概念呢?例如有时间戳的东西(HasTimestamp、Tim
我刚开始学习 PowerShell,我想知道 Posh 中的 cmdlet(或高级功能,无论它们在 CTP3 中称为什么)是否有一些好的动词指南。 如果我做一个get-verb,我可以看到很多。但我仍
$(".song").live('click', function songClick() { //do stuff }); 你能像上面那样命名一个函数,然后稍后再调用它吗?我尝试过,但没有成
关闭。这个问题是opinion-based .它目前不接受答案。 想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它. 7年前关闭。 Improve this
我的 Spring 应用程序中有两组类 - DTO 和实体。 在阅读了 Bob 叔叔的 Clean Code 之后,我比以往任何时候都更喜欢正确命名事物。 我坐下来重构我的一个 Spring 项目,但
我是一名优秀的程序员,十分优秀!