Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient: Python docstrings or type-hints?

Tags:

I want to add some support for auto-completion to my Python code with Jedi. This can be done by using either function docstrings or type hints (or both).

def function_with_types_in_docstring(param1, param2):     """Example function with types documented in the docstring.      :type param1: int     :type param2: str     :rtype: bool     """  def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:     """Example function with PEP 484 type annotations.""" 

Which method of documenting types adds less overhead in terms of memory usage and running time? I'm interested in the efficiency of the Python code itself first, then Jedi.

like image 699
planetp Avatar asked Jun 06 '17 12:06

planetp


1 Answers

TL;DR: Use type annotations, they are awesome.

For both Python and jedi it does not make a difference wheter you use docstrings or function annotations. Both performance and memory impact should not be noticeable. There is obviously a small runtime overhead in both cases.

Docstrings are simply converted to Python strings and stored in the attribute function.__doc__. This takes a few bytes of memory, but you shouldn't care about that. A very large docstring of 1000 characters still only uses 1kB of RAM. If your memory is constrained you may simply use python -o to get rid of docstrings (and asserts as well, look it up).

Type annotations (PEP 484, e.g. def foo(a: int) -> str:) are stored in function.__annotations__:

>>> def foo(bar: int): pass ...  >>> foo.__annotations__ {'bar': <class 'int'>} 

These annotations obviously also use some space (but even less than docstrings). However they have no influence on runtime execution (except if you explicitly play with __annotations__.

I would recommend you to use type annotations. They have been introduced, because of static analysis/IDEs and are definitely the future when it comes to documenting your types. There's also a lot of work happing on mypy, jedi and other tools to make type annotations more usable in verifying programs. Use type annotations already and you will be ready for the future.

like image 187
Dave Halter Avatar answered Oct 18 '22 05:10

Dave Halter