Blender has an embedded Python interpreter which is loaded when Blender is started and stays
active while Blender is running. This interpreter runs scripts to draw the user interface
and is used for some of Blender’s internal tools as well.

Blender’s embedded interpreter provides a typical Python environment, so code from tutorials
on how to write Python scripts can also be run with Blender’s interpreter. Blender provides its
Python modules, such as bpy and mathutils, to the embedded interpreter so they can
be imported into a script and give access to Blender’s data, classes, and functions. Scripts that
deal with Blender data will need to import the modules to work.

Here is a simple example which moves a vertex attached to an object named Cube:

importbpybpy.data.objects["Cube"].data.vertices[0].co.x+=1.0

This modifies Blender’s internal data directly.
When you run this in the interactive console you will see the 3D viewport update.

When developing your own scripts it may help to understand how Blender sets up its Python environment.
Many Python scripts come bundled with Blender and can be used as a reference
because they use the same API that script authors write tools in.
Typical usage for scripts include: user interface, import/export,
scene manipulation, automation, defining your own toolset and customization.

On startup Blender scans the scripts/startup/ directory for Python modules and imports them.
The exact location of this directory depends on your installation.
See the directory layout docs.

This may seem obvious, but it is important to note the difference between
executing a script directly and importing a script as a module.

Extending Blender by executing a script directly means the classes that the script
defines remain available inside Blender after the script finishes execution.
Using scripts this way makes future access to their classes
(to unregister them for example) more difficult compared to importing the scripts as modules.
When a script is imported as a module, its class instances will remain
inside the module and can be accessed later on by importing that module again.

For this reason it is preferable to avoid directly executing scripts that extend Blender by registering classes.

Here are some ways to run scripts directly in Blender.

Loaded in the text editor and press Run Script.

Typed or pasted into the interactive console.

Execute a Python file from the command line with Blender, eg:

blender --python /home/me/my_script.py

To run as modules:

The obvious way, importsome_module command from the text window or interactive console.

Open as a text block and tick “Register” option, this will load with the blend file.

copy into one of the directories scripts/startup, where they will be automatically imported on startup.

define as an add-on, enabling the add-on will load it as a Python module.

Some of Blenders functionality is best kept optional,
alongside scripts loaded at startup we have add-ons which are kept in their own directory scripts/addons,
and only load on startup if selected from the user preferences.

The only difference between add-ons and built-in Python modules is that add-ons must contain a bl_info
variable which Blender uses to read metadata such as name, author, category and URL.

The User Preferences add-on listing uses bl_info to display information about each add-on.

This is intentionally limited. Currently, for more advanced features such as mesh modifiers,
object types, or shader nodes, C/C++ must be used.

For Python integration Blender defines methods which are common to all types.
This works by creating a Python subclass of a Blender class which contains variables and functions
specified by the parent class which are pre-defined to interface with Blender.

Notice these classes don’t define an __init__(self) function.
While __init__() and __del__() will be called if defined,
the class instances lifetime only spans the execution.
So a panel for example will have a new instance for every redraw,
for this reason there is rarely a cause to store variables in the panel instance.
Instead, persistent variables should be stored in Blenders
ata so that the state can be restored when Blender is restarted.

Note

Modal operators are an exception, keeping their instance variable as Blender runs, see modal operator template.

So once the class is registered with Blender, instancing the class and calling the functions is left up to Blender.
In fact you cannot instance these classes from the script as you would expect with most Python API’s.

To run operators you can call them through the operator api, eg:

importbpybpy.ops.object.simple_operator()

User interface classes are given a context in which to draw, buttons window, file header, toolbar etc,
then they are drawn when that area is displayed so they are never called by Python scripts directly.

These functions usually appear at the bottom of the script containing class registration sometimes adding menu items.
You can also use them for internal purposes setting up data for your own tools but take care
since register won’t re-run when a new blend file is loaded.

The register/unregister calls are used so it’s possible to toggle add-ons and reload scripts while Blender runs.
If the register calls were placed in the body of the script, registration would be called on import,
meaning there would be no distinction between importing a module or loading its classes into Blender.

This becomes problematic when a script imports classes from another module
making it difficult to manage which classes are being loaded and when.

The last 2 lines are only for testing:

if__name__=="__main__":register()

This allows the script to be run directly in the text editor to test changes.
This register() call won’t run when the script is imported as a module
since __main__ is reserved for direct execution.

Registering a class with Blender results in the class definition being loaded into Blender,
where it becomes available alongside existing functionality.

Once this class is loaded you can access it from bpy.types,
using the bl_idname rather than the classes original name.

When loading a class, Blender performs sanity checks making sure all required properties and functions are found,
that properties have the correct type, and that functions have the right number of arguments.

Mostly you will not need concern yourself with this but if there is a problem
with the class definition it will be raised on registering:

Using the function arguments defexecute(self,context,spam), will raise an exception:

When customizing Blender you may want to group your own settings together,
after all, they will likely have to co-exist with other scripts.
To group these properties classes need to be defined,
for groups within groups or collections within groups
you can find yourself having to deal with order of registration/unregistration.

Custom properties groups are themselves classes which need to be registered.

# Create new property group with a sub property# bpy.data.materials[0].my_custom_props.sub_group.my_floatimportbpyclassMyMaterialSubProps(bpy.types.PropertyGroup):my_float:bpy.props.FloatProperty()classMyMaterialGroupProps(bpy.types.PropertyGroup):sub_group:bpy.props.PointerProperty(type=MyMaterialSubProps)defregister():bpy.utils.register_class(MyMaterialSubProps)bpy.utils.register_class(MyMaterialGroupProps)bpy.types.Material.my_custom_props:bpy.props.PointerProperty(type=MyMaterialGroupProps)defunregister():delbpy.types.Material.my_custom_propsbpy.utils.unregister_class(MyMaterialGroupProps)bpy.utils.unregister_class(MyMaterialSubProps)if__name__=="__main__":register()

Note

The lower most class needs to be registered first and that unregister() is a mirror of register()