PyCharm 2024.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 __init__.py). 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 __init__.py file contains all code from the .py file.

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

Now that you created a package, you can do the following:

  • Import the package into the project files. Use code completion to discover it.

  • Commit and push the package into a VCS repository.

  • Install the package in a virtual environment locally or from VCS so that you can use it in your other projects with that environment.

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 __init__.py file. See Copy and Move Refactorings for more details. This is the key action, because only an empty package (a package that has no files but the __init__.py file) can be converted into a module.

  2. Select the package.

  3. Select Refactor | Convert to Python Module.

    converting a package to a module
  4. Inspect the project: the .py file named as the converted package is created; it contains code from the __init__.py file

Last modified: 11 February 2024