Code completion not giving recommendations

As Python is a dynamically typed language, you need to ensure it can work out what type things are, and inspect on the libraries on your system correctly. Try to make sure it’s obvious what type the object is in your code.

One good way as of PyCharm 2.7 (back when versions were numbers) is to enable runtime type detection – PyCharm hooks into your program while it runs (while debugging), and checks the types of variables as they are used.

You can enable this by going to settings, going to the “Build, Execution, Deployment” section and then the “Python Debugger” subsection and enabling “Collect run-time types information for code insight”.

The settings screen of PyCharm open to show the relevant setting.

Obviously it is worth noting that this isn’t perfect – if you make changes, this won’t be updated til the code is executed, and it can only tell you about values it has seen – other code paths you haven’t tried could set other types.

You can also ‘tell’ PyCharm by using Epydoc or Sphinx style docstrings that contain information about parameter and return value types. PyCharm will use these to improve it’s inspections.

Python also gained support for function annotations as of Python 3. These can be used for type hints as per PEP 484. See the typing module for more. This is more formal, so it can also be used for tools like mypy which a type checker that can programmatically check these types for consistency, giving Python a TypeScript-style optional static typing.

Leave a Comment