PyCharm 2021.1 Help

Convert to Package and Module

PyCharm lets you safely restructure your source files by converting a Python module to a Python package and vise versa.

Convert to a Python package

A package typically is a directory that contains modules and initialization code (file A module is a .py source file with Python definitions that can be imported to other modules.

To convert a Python module to a Python package

  1. Select a .py file.

  2. Select Refactor | Convert to Python Package.

    Refactor a Python module to a package

  3. Inspect the project: the package named as the converted module is created; the file contains all code from the .py file.

With the package created, you can add more new modules to it, or you can use Move Refactorings to derive modules from the initial implementation. You can also modify the file to put some initialization code for the package or list all the added modules by using the __all__ variable.

Convert to a Python module

You might need to consolidate all modules from a package into a single module.

To convert a Python package to a Python module

  1. Prepare your package for refactoring: move code from all modules in the package to the file. See Move Refactorings for more details. This is the key action, because only an empty package (a package that has no files but the file) can be converted into a module.

  2. Select the package.

  3. Select Refactor | Convert to Python Module.

    Py refactoring convert to module

  4. Inspect the project: the .py file named as the converted package is created; it contains code from the file

Last modified: 08 March 2021