如何用动态类型语言描述函数参数? [英] How to describe function arguments in dynamic typed languages?

查看:107
本文介绍了如何用动态类型语言描述函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题更倾向于Python,但也可能是关于JavaScript或其他脚本语言。

My question is more oriented toward Python, but it may also be about JavaScript or other scripting languages.

我通常使用静态类型语言(Java,C ++, ActionScript,...)。

I usually develop with statically typed languages (Java, C++, ActionScript, ...).

我喜欢不时使用Python,我还需要有时使用JavaScript。这些是动态类型语言。这没有什么不对,但我通常有很多麻烦来理解函数或方法中需要哪些参数。它发生即使它是我自己的代码与一些docstrings!也许是因为眼睛必须在其他地方看而不是在函数的定义中。

I like to use from time to time Python, and I also need to sometimes use JavaScript. These are dynamic typed languages. Nothing wrong with that, but I usually have lots of headaches to understand which parameters are needed in a function or in a method. It happens even if it is my own code with some docstrings! Maybe because the eye has to look somewhere else than in the definition of the function.

当然,答案应该在文档中。但有时它根本不清楚,或者因为使用duck typing,文档本身很难写(第一个参数是一个必须有quack()方法和羽毛(arg)的函数方法,其中arg是字符串)。我非常喜欢的是语言本身内部的一种参数描述(即使它是可选的,就像在ActionScript中一样)。

Of course, the answer should be in the documentation. But sometimes it is not clear at all, or because of the use of duck typing the documentation may be itself hard to write ("the first parameter is a function which must have a quack() method and a feathers(arg) method where arg is a string"). What I would very like is a kind of argument description inside the language itself (even if it would be optionnal, like in ActionScript).

你明确的最佳做法是什么?描述函数/方法的参数?

What are your best practices to unambiguously describe the arguments of a function/method?

如何创建一个特殊的装饰器(如果使用Python),其目的是在我们使用它时检查数据的类型(但是因为它将在运行时而不是在写入时使用,无论如何都会有什么意义?)

What about creating a special decorator (if using Python) which purpose would be to check the type of data when we use it (but as it will be used at runtime and not at writing time, what would be the point anyway)?

你认为这应该不是问题吗?比当前docstring更多的东西会让开发人员感到困惑,或者我的思维过于静态 - 打字导致?

Do you think it should not be an issue? That doing more than current docstring would confuse a developer, or that my mind is too static-typing oriented?

推荐答案

我不喜欢知道Javascript,但Python从版本3开始有可选的函数注释,如下所示:

I don't know about Javascript, but Python has optional function annotations since version 3, which look like:

def haul(item: Haulable, *vargs: PackAnimal) -> Distance:

或:

def compile(source: "something compilable",
            filename: "where the compilable thing comes from",
            mode: "is this a single statement or a suite?"):

参见 PEP 了解更多信息。

它们可以在运行时访问,甚至可以用于类型检查

They are accessible at runtime and may even be used for type checking.

这篇关于如何用动态类型语言描述函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆