Search code examples
javascriptpythonargumentsdynamic-typingcode-documentation

How to describe function arguments in dynamic typed languages?


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

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

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.

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?

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)?

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?


Solution

  • 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.