How to Create Stub File in Python using PyCham ?

How to Create Stub File in Python using PyCham ?

Swaroop Kumar Yadav

What is Stub in Python?

Create a stub file for your own implementation

  1. Navigate to the directory where the target implementation resides. Select File | New from the main menu, then select Python File (alternatively, use the Alt+Insert shortcut).
  2. In the New Python file dialog, select Python stub and specify the filename. The filename should be the same as the name of the implementation file.
Press Enter to complete the action.

For your convenience, you can create a separate directory to keep your stub and its implementation. This will help you reuse the stub for your other projects.


Create a stub file for the external implementation

You can create a stub file for some implementations that reside in the packages installed in your environments.

  1. Create a directory for your stub. Right-click the directory and from the context menu select Mark directory as | Source Root.
  2. In the directory, recreate the hierarchy corresponding to the implementation package.

3. Within the created structure, navigate to the target directory and select File | New from the main menu, then select Python File (alternatively, use the Alt+Insert shortcut). In the New Python file dialog, select Python stub and specify the filename. Press Enter and the file will be created. You can put any other required files to the stub directory.

PyCharm shows an asterisk in the left gutter for those code elements that have stubs. Click the asterisk to jump between a stub and its implementation:

Reuse stubs

You can make your stubs accessible for your other PyCharm projects.

1. Click the Project Interpreter selector in the Status Bar and select Interpreter Settings.

2. In the Project Interpreter dialog, click Browse and select Show All, then in the opened Project Interpreters dialog, click Show paths for the selected interpreter.

3. In the Interpreter paths dialog, click the Add button to add the new path record:

4. Inspect your project: the directory with the stub files is now marked as a library root.

Any time you will use this project interpreter to work with other projects, this stub library will be accessible through the path you have just added.

Install a Stub Package

For the more widely use, you can create a stub package and upload to the pypi repository. See more information in the Packaging Python Projects guide. With the PEP-561 support, you can install stubs packages for your project interpreter.

1. Install the package. If needed, click Manage repositories to add a repository where your stub packages reside.

2. Stub packages have a predefined name format, so type "-stubs" in the search field to discover them.

3. Click Install Package to complete installation.

Was this page helpful?

Join us on TELEGRAM for Daily Python with quizzes & tips and tricks.


Report Page