How to describe function arguments in dynamic typed languages?

五迷三道 提交于 2019-12-05 13:15:14

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:

or:

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

see the PEP for more information.

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

Why does duck typing make the documentation hard to write?

When ever you write a function, you write it assuming the arguments are of a particular type or confirm to a particular interface… So just document that.

For example, if you have a swim_in_pond(duck) method, there's no need to document "duck is expected to have quack(), swim(), and dive() methods" — in most cases, it's entirely sufficient to say "duck is an instance of Duck". Or, if it's important for you to document the "Duck-like" interface, I've found it helpful to declare a base class which serves as the documentation:

class DuckBase(object):
    def quack(self):
        """ Makes the duck quack. """

    def swim(self):
        """ Swims around.
            Assumes the duck is already in water.
            Updates the duck's position. """

    def dive(self):
        """ Dives either as deep as possible (either until the duck runs out of
            air, or it hits the bottom of the pond). """
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!