FeaturePython Objects

Introduction
FeaturePython objects (also often referred to as 'Scripted Objects') provide users the ability to extend FreeCAD's with objects that integrate seamlessly into the FreeCAD framework.

This encourages:


 * Rapid prototyping of new objects and tools with custom Python classes.


 * Serialization through 'App::Property' objects, without embedding any script in the FreeCAD document file.


 * Creative freedom to adapt FreeCAD for any task!

This wiki will provide you with a complete understanding of how to use FeaturePython objects and custom Python classes in FreeCAD. We're going to construct a complete, working example of a FeaturePython custom class, identifying all of the major components and gaining an intimate understanding of how everything works as we go.

How Does It Work?
FreeCAD comes with a number of default object types for managing different kinds of geometry. Some of them have 'FeaturePython' alternatives that allow for user customization with a custom python class.

The custom python class simply takes a reference to one of these objects and modifies it in any number of ways. For example, the python class may add properties directly to the object, modifying other properties when it's recomputed, or linking it to other objects. In addition the python class implements certain methods to enable it to respond to document events, making it possible to trap object property changes and document recomputes.

It's important to remember, however, that for as much as one can accomplish with custom classes and FeaturePython objects, when it comes time to save the document, only the FeaturePython object itself is serialized. The custom class and it's state are not retained between document reloading. Doing so would require embedding script in the FreeCAD document file, which poses a significant security risk, much like the risks posed by embedding VBA macros in Microsoft Office documents.

Thus, a FeaturePython object ultimately exists entirely apart from it's script. The inconvenience posed by not packing the script with the object in the document file is far less than the risk posed by running a file embedded with an unknown script. However, the script module path is stored in the document file. Therefore, a user need only install the custom python class code as an importable module following the same directory structure to regain the lost functionality.

Setting up your development environment
To begin, FeaturePython Object classes need to act as importable modules in FreeCAD. That means you need to place them in a path that exists in your Python environment (or add it specifically). For the purposes of this tutorial, we're going to use the FreeCAD user Macro folder, though if you have another idea in mind, feel free to use that instead!

Anyway, if you don't know where the FreeCAD Macro folder is:


 * OS-independent: Type 'FreeCAD.getUserMacroDir(False)' in FreeCAD's Python console


 * Windows: Type '%APPDATA%/FreeCAD/Macro' in the filepath bar at the top of Explorer


 * Linux: Navigate to /home/USERNAME/.FreeCAD/Macro


 * Mac: Navigate to /Users/USERNAME/Library/Preferences/FreeCAD/Macro

Now we need to create some files.


 * In the Macro folder create a new folder called fpo.
 * In the fpo folder, create a new folder called box.
 * In the box folder create two files: __init__.py and box.py (leave both empty for now)

The fpo folder provides a nice spot to play with new FeaturePython objects and the box folder is the module we will be working in.

__init__.py tells Python that in the folder is an importable module, and box.py will be the class file for our new FeaturePython Object

Your directory structure should look like this:

.FreeCAD |--> Macro |--> fpo |--> box |--> __init__.py                 |--> box.py

With our module paths and files created, let's make sure FreeCAD is set up properly. If FreeCAD isn't loaded, now is a good time to boot it up.

Make sure the Python Console and Report View are enabled by selecting View -> Panels -> Report view and Python console

If you haven't been introduced to the Python Console in FreeCAD, you can learn more about it here

Now that FreeCAD is set up, switch over to your favorite code editor, navigate to the Macro/fpo/box folder, and open box.py. It's time to write some code!

-

A Very Basic FeaturePython Object
We're going to start really simply. It won't be impressive, but it will provide a clear idea of how FeaturePython objects work with custom python classes.

So, let's get started by writing our class and it's constructor:

class box: def __init__(self, obj): """         Default Constructor          """ self.Type = 'box' obj.Proxy = self self.Object = obj

This small piece of code illustrates just how FeaturePython objects interact with Python classes. We'll examine that in more detail momentarily, but first we need to add a little more code to manage object creation. In the box.py file at the top, add the following code:

import FreeCAD as App def create(obj_name): """     Object creation method      """ obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name) fpo = box(obj) return fpo

The  method is not required, but it provides a nice way to encapsulate the object creation code. -

Testing the Code
Now we can try our new object. Save your code and return to FreeCAD, make sure you've opened a new document. You can do this by pressing CTRL+n or selecting File -> New In the Python Console, type the following:

>>> from fpo.box import box

Now, we need to create our object:

>>> box.create('my_box') You should see a new object appear in the tree view at the top left labelled my_box. Note that the icon is gray. FreeCAD is simply telling us that the object is not able to display anything in the 3D view... yet. Click on the object and note what appears in the property panel under it. There's not very much - just the name of the object. We'll need to add some properties in a bit. Let's also make referencing our new object a little more convenient:

>>> mybox = App.ActiveDocument.my_box

Let's inspect the list of attributes:

>>> dir(mybox) ['Content', 'Document', 'ExpressionEngine', 'InList', 'InListRecursive', 'Label', 'MemSize', 'Module', 'Name', 'OutList', 'OutListRecursive', 'PropertiesList', 'Proxy', 'State', 'TypeId', 'ViewObject', '__class__', ... 'setEditorMode', 'setExpression', 'supportedProperties', 'touch']

There's a lot of attributes there! That's because we're accessing the native FreeCAD FeaturePyton object that we created in the first line of our  method. The  property we added in our   method is there, too. Let's inspect that:

>>> dir(mybox.Proxy) ['Object', 'Type', '__class__', '__delattr__', '__dict__', '__dir__', ... '__str__', '__subclasshook__', '__weakref__']

Among the list of protected methods and properties, we see our  and   properties!

Call the  property and look at the result: >>> mybox.Proxy.Type 'box'

Sure enough, it returns the value we assigned, so we know we're accessing the custom class itself through the FeaturePython object. Likewise, if you call: >>> mybox.Proxy.Object

You'll get back the FeaturePython Object, the same thing that  refers to.

That was fun! But now let's see if we can make our class a little more interesting... and maybe more useful. -

Adding Properties
Properties are the lifeblood of a FeaturePython class. Fortunately, FreeCAD supports a number of property types for FeaturePython classes. These properties are attached directly to the FeaturePython object itself and fully serialized when the file is saved. That means, unless you want to serialize the data yourself, you'll need to find some way to wrangle it into a supported property type. Adding properties is done quite simply using the  method. The syntax for the method is:

add_property(type, name, section, description)

Let's try adding a property to our box class. Switch to your code editor and move to the  method.

Then, at the end of the method, add:

obj.addProperty('App::PropertyString', 'Description', 'Base', 'Box description').Description = ""

Note how we're using the reference to the (serializable) FeaturePython object,  and not the (non-serializable) Python class instanace,. Anyway, once you're done, save the changes and switch back to FreeCAD. Before we can observe the changes we made to our code, we need to reload the module. This can be accomplished by restarting FreeCAD, but restarting FreeCAD everytime we make a change to the python class code can get a bit inconvenient. To make it easier, try the following in the Python console:

>>> from importlib import reload >>> reload(box)

This will reload the box module, incorporating changes you made to the box.py file, just as if you'd restarted FreeCAD. With the module reloaded, now let's see what we get when we create an object:

>>> box.create('box_property_test') You should see the new box object appear in the tree view at left. But before we leave the topic of properties for the moment, let's go back and add some properties that would make a custom box object *really* useful: namely, length, width, and height. Return to your source code and add the following properties to
 * Select it and look at the Property Panel. There, you should see the 'Description' property.
 * Hover over the property name at left and see the tooltip appear with the description text you provided.
 * Select the field and type whatever you like. You'll notice that Python update commands are executed and displayed in the console as you type letters and the property changes.

obj.addProperty('App::PropertyLength', 'Length', 'Dimensions', 'Box length').Length = 1.0 obj.addProperty('App::PropertyLength', 'Width', 'Dimensions', 'Box width').Width = '10 mm' obj.addProperty('App::PropertyLength', 'Height', 'Dimensions', 'Box height').Height = '1 cm'

One last thing: Did you notice how the blue checkmark appears next to the FeaturePython object in the treeview at left? That's because when an object is created or changed, it's "touched" and needs to be recomputed. Clicking the "recycle" arrows (the two arrows forming a circle) will accomplish this. But, we can accomplish that automatically by adding the following line to the end of the  method:

App.ActiveDocument.recompute Now, test your changes as follows: Once the box is created (and you've checked to make sure it's been recomputed!), select the object and look at your properties. You should note two things: Note also how the properties have dimensions. Specifically, they take on the linear dimension of the units set in the user preferences (see Edit -> Preference... -> Units tab). In fact, if you were paying attention when you were entering the code, you will have noticed that three separate values were entered for each dimension. The length was a floating-point value (10.0), the width was a string, specifying millimeters ('10 mm') and the height was a string specifying centimeters ('1 cm'). Yet, the property rendered all three values the same way: 10 mm. Specifically, a floating-point value is assumed to be in the current document units, and the string values are parsed according to the units specified, then converted to document units. The nice thing about the  type is that it's a 'unit' type - values are understood as having specific units. Therefore, whenever you create a property that uses linear dimensions, use  as the property type. -
 * Save your changes and return to FreeCAD.
 * Delete any existing objects and reload your module.
 * Finally, create another box object from the command line by calling.
 * Three new properties (length, width, and height)
 * A new property group, Dimensions.

Event Trapping
The last element required for a basic FeaturePython object is event trapping. Specifically, we need to trap the  event, which is called when the object is recomputed. There's several other document-level events that can be trapped in our object as well, both in the FeaturePython object itself and in the ViewProvider, which we'll cover in another section. Add the following after the  function:

def execute(self, obj): """    Called on document recompute     """ print('Recomputing {0:s} ({1:s})'.format(self.Object.Name, self.Type))

Test the code as follows:

You should see the printed output in the Python Console, thanks to the  call we added to the   method.
 * Save changes and reload the box module in the FreeCAD python console.
 * Delete any objects in the Treeview
 * Re-create the box object.

Of course, the  method doesn't do anything here (except tell us that it was called), but it is the key to the magic of FeaturePython objects.

So that's it! You now know how to build a basic, functional FeaturePython object!

The complete code for the object thus far:

import FreeCAD as App def create(obj_name): """   Object creation method    """ obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name))   fpo = box(obj)    return fpo class box:    def __init__(self, obj):        """        Default Constructor        """        self.Type = 'box'        obj.addProperty('App::PropertyString', 'prop', 'ppp').prop = 'Hello World!'        obj.addProperty('App::PropertyLength', 'Length', 'Box length').prop = 1.0        obj.addProperty('App::PropertyLength', 'Width', 'Box width'). prop = 1.0        obj.addProperty('App::PropertyLength', 'Height', 'Box Height').prop = 1.0        obj.Proxy = self        self.Object = obj    def execute(self, obj):        """        Called on document recompute        """        print('Recomputing {0:s} {1:s}'.format(self.Object.Name, self.Type))