Export shape keys

Greetings,

I am writing an exporter in python and I want to add shape keys export.
I have a mesh with shape keys.

When I try to access “object.data.shape_keys” (object being of type “MESH”) from Python, the shape_keys is always None.
When I mouse over the shape keys related field in the blender GUI, I can see something like bpy.data.shape_keys(“Key”).<some_var_name>.
And indeed, if I iterate over bpy.data.shape_keys, I can access my mesh shape_keys.
I just do not understand why “object.data.shape_keys” is None even though the shape keys clearly exist and are functional.
I have checked some other scripts in the addon folder, and they seem to accept the shape_keys via the object.data, but always check for None first.

The shape keys values of my mesh are controlled via drivers. I am not sure if it is relevant or not.
What is the proper way to access a mesh shape keys from python?

Thanks in advance.

bpy.context.active_object.data.shape_keys.key_blocks[0] is the basis shape key, for example.

In my case, the active_object.data.shape_keys is None, even though I can access the shape keys through bpy.data.shape_keys dict.
It is really weird, I wonder if the data I have is corrupted.
Thanks for your help though.

Are you sure the correct object is active?

I tried again and indeed the method suggested by PythonFan just works.

It is not usable for an exporter though, as I just want to iterate through all meshes in the file and extract shape keys for each of them.
But actually I just found the bug in my export script.
I was trying to get the shape keys information from a mesh created via the object.to_mesh method.
Since I apply modifiers and ask for an undeformed mesh, I guess the shape keys info is just ripped from it.
By checking the object.data directly, I can access shape keys info normally.

Thank you both of you, you put me on the right track to fix my buggy script.

Object.to_mesh()'s last parameter allows you to apply modifiers but not take deformation into account:

Object.to_mesh(scene, apply_modifiers, settings, calc_tessface=True, calc_undeformed=False)

You might wanna set that to True.

Hi all

Hello I used the CodemanX solution in order to export shapekeys from version 2.6.2.
It work perfectly until then. But recently an update in Blender changed the expected behavior of:
Object.to_mesh(scene, apply_modifiers, settings, calc_tessface=True, calc_undeformed=False)

Before: mesh were constructed with active keyshapes weigthing (resulting in a different mesh)
Now: mesh is contructed with original vertices and the keyshapes are shallow copied from the object (resulting in the same mesh as object original)

Could anyone give me advices in order my exporter work again…please