设计 Python API:流畅的接口或参数

发布于 2024-09-26 16:50:02 字数 753 浏览 13 评论 0原文

我正在尝试将 Protovis API 移植到 Python。

考虑一下 Javascript 中的简单条形图示例:

var vis = new pv.Panel()
    .width(150)
    .height(150);

vis.add(pv.Bar)
    .data([1, 1.2, 1.7, 1.5, .7, .3])
    .width(20)
    .height(function(d) d * 80)
    .bottom(0)
    .left(function() this.index * 25);

vis.render();

我正在争论是继续使用这种流畅的界面风格 API 还是使用命名参数。使用命名参数,我们可以编写:

vis = pv.Panel(width=150,
               height=150)

vis = vis + pv.Bar(data=[1, 1.2],
                   width=20,
                   height=lambda d: d * 80,
                   bottom=0,
                   left=lambda: self.index * 25)
vis.render()

有首选的 Python 风格吗?

I'm playing around with a simple port of the Protovis API to Python.

Consider the simple bar chart example, in Javascript:

var vis = new pv.Panel()
    .width(150)
    .height(150);

vis.add(pv.Bar)
    .data([1, 1.2, 1.7, 1.5, .7, .3])
    .width(20)
    .height(function(d) d * 80)
    .bottom(0)
    .left(function() this.index * 25);

vis.render();

I'm debating whether to continue to use this fluent interface style API or use named parameters instead. With named parameters we could write:

vis = pv.Panel(width=150,
               height=150)

vis = vis + pv.Bar(data=[1, 1.2],
                   width=20,
                   height=lambda d: d * 80,
                   bottom=0,
                   left=lambda: self.index * 25)
vis.render()

Is there a preferred Python style?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不及他 2024-10-03 16:50:02

我的投票是反对链接,支持命名参数。

  1. 点链接会导致代码智能感知较差,因为经验原型只是一个空的 Panel() 或 Bar(),您当然可以对其进行 pydoc,但在当今时代,智能感知在大多数 IDE 中都可用,并且伟大的生产力助推器。

  2. 链接使得以编程方式调用类变得更加困难。能够将列表或字典作为 *args、**kwargs 传递是非常好的——虽然可以使用链接,但您基本上必须支持这两种方法或一堆后空翻来元创建类。

  3. 链接使代码更难以阅读,因为不可避免地有人会在一行上完成所有操作,并想知道为什么当他们两次传递相同的参数时事情都会变得很糟糕——你可以防止这种情况,但使用命名参数构造函数 dup 过滤基本上是内置的。

My vote is anti-chaining, pro-named-params.

  1. dot-chaining makes for poor code-intellisense since the empirical prototype is just an empty Panel() or Bar(), you can of course pydoc on it, but in this day and age intellisense is available in most IDEs and a great productivity booster.

  2. Chaining makes programatically calling the class much more difficult. It's very nice to be able to pass in a list or dict as *args, **kwargs -- while possible with chaining you'd basically have to support both methods or a bunch of backflips to meta-create the class.

  3. Chaining makes code more difficult to read because inevitably someone will do it all on one line, and wonder why things are all goofed up when they've passed in the same param twice -- you can prevent that but with a named param constructor dup filtering is basically built in.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文