documentation index ◦ reference manual ◦ function index

# Python Modules

It's possible to write python modules, and import them into Ren'Py. These python modules define their own namespace, which is different from the namespace in which python-in-Ren'Py executes. Objects defined in python modules do not participate in rollback, although they may be saved if they are reachable from the main Ren'Py store.

Python modules may be placed in the game directory, while python packages are subdirectories of the game directory containing __init__.py files. The only encoding we support is utf-8.

We suggest beginning each module with:

    import renpy.store as store
    import renpy.exports as renpy

This makes the store, the namespace in which python-in-Ren'Py executes, available as `store`. It also makes the various functions documented in this manual available under `renpy`. (A simple `import renpy` will not do this, it will access the internals of Ren'Py instead. Sorry for the additional complexity.)

In general, objects created inside python modules do not participate in rollback. This means that you should not change such objects after their initial creation. If you want to produce an object that participates in rollback, you can use the equivalents defined in the `store` module: `store.list`, `store.dict`, `store.set`, `store.object`. You can also create a class inheriting from `store.object`, and objects of that class will participate in rollback.

It's probably easier to not change objects that are created in python modules.

## Example

As a trivial example, we could have the following module, which is placed in magic.py in the game directory.

    import renpy.store as store
    import renpy.exports as renpy

    def add(a, b):
        return a + b

In a Ren'Py script file, we can import the module using an import statement:

    init:
        $ import magic

You can then call methods from the module:

    $ result = magic.add(1, 2)

    "1 + 2 = %(result)d"

documentation index ◦ reference manual ◦ function index