Create a FeaturePython object part I

From FreeCAD Documentation
Revision as of 08:24, 4 June 2020 by Roy 043 (talk | contribs) (Revising...)
This documentation is a work in progress. Please don't mark it as translatable since it will change in the next hours and days.

Introduction

FeaturePython objects (also often referred to as Scripted objects) provide users the ability to extend FreeCAD 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 to the object, modify other properties when it's recomputed, or link it to other objects. In addition the python class may implement certain methods to enable the object to respond to document events, making it possible to trap object property changes and document recomputes.

When working with custom classes and FeaturePython objects it is important to know that, when it comes time to save the document, only the FeaturePython object itself is serialized. The custom class and it's state are not saved in the document as this would require embedding a script in a FreeCAD document file, which would pose a significant security risk.

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.

top

Setting things up

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. But if you have another idea in mind, feel free to use that instead.

If you don't know where the FreeCAD Macro folder is type FreeCAD.getUserMacroDir(True) in FreeCAD's Python console:

  • On Linux it is usually /home/<username>/.FreeCAD/Macro/.
  • On Windows it is %APPDATA%\FreeCAD\Macro\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Macro\.
  • On Mac OSX it is usually /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 an empty file: __init__.py.
  • 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).

Your directory structure should look like this:

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

The fpo folder provides a nice place to play with new FeaturePython objects and the box folder is the module we will be working in. __init__.py tells Python that there is an importable module in the folder, and box.py will be the class file for our new FeaturePython Object.

With our module paths and files created, let's make sure FreeCAD is set up properly:

Finally, navigate to the Macro/fpo/box folder and open box.py in your favorite code editor.

top

A FeaturePython object

Let's get started by writing our class and it's constructor:

class box():

    def __init__(self, obj):
        """
        Constructor
        
        Arguments
        ---------
        - obj: an existing document object or an object created with FreeCAD.Document.addObject('App::FeaturePython', '{name}').
        """

        self.Type = 'box'
  
        obj.Proxy = self

The __init__() method breakdown:

def __init__(self, obj): Parameters refer to the Python class itself and the FeaturePython object that it is attached to
self.Type = 'box' String definition of the custom python type
obj.Proxy = self Stores a reference to the Python instance in the FeaturePython object

Still in the box.py file, add the following code at the top:

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 create() method breakdown:

import FreeCAD as App Standard import for most Python scripts, the App alias is not required
obj = ... addObject(...) Creates a new FreeCAD FeaturePython object with the name passed to the method. If there is no name clash, this will be the label and the name of the created object, i.e. what is visible in the model tree. Otherwise, a unique name and label will be created based on 'obj_name'.
fpo = box(obj) Create our custom class instance and link it to the FeaturePython object.

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

top

Testing the code

Now we can test our new object. Save your code and return to FreeCAD. Make sure you have 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 labelled "my_box".

Note that the icon is gray. FreeCAD is telling us that the object, for now at least, is not able to display anything in the 3D view. Click on the object and note what appears in the Property editor. There is not very much, just the name of the object. We'll add some properties later.

Let's make referencing our new object a little more convenient:

mybox = App.ActiveDocument.my_box

And then we should take a look at our object's attributes:

dir(mybox)

This will return:

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

There are a lot of attributes because we're accessing the native FreeCAD FeaturePyton object created in the first line of our create() method. The Proxy property we added in our __init__() method is there, too.

Let's inspect it with the dir() method:

dir(mybox.Proxy)

This will return:

['Type', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
...
'__str__', '__subclasshook__', '__weakref__']

We can see our Type property. Let's check it:

mybox.Proxy.Type

This will return:

'box'

This is indeed the assigned value, so we know we're accessing the custom class through the FeaturePython object.

Now let's see if we can make our class a little more interesting, and maybe more useful.

top

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 and are fully serialized when the file is saved. 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 using the add_property() method. The syntax for the method is:

add_property(type, name, section, description)

You can view the list of supported properties for an object by typing:

mybox.supportedProperties()

Let's try adding a property to our box class. Switch to your code editor, move to the __init__() method, and 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, obj, and not the (non-serializable) Python class instance, self.

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 every time we make a change to the code would be 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, 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.

  • Select it and look at the Property editor. 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.

Let's add some more properties that would make a custom box object really useful. Return to your source code and add the following properties to the __init__() method:

obj.addProperty('App::PropertyLength', 'Length', 'Dimensions', 'Box length').Length = 10.0
obj.addProperty('App::PropertyLength', 'Width', 'Dimensions', 'Box width').Width = '10 mm'
obj.addProperty('App::PropertyLength', 'Height', 'Dimensions', 'Box height').Height = '1 cm'
File:Object recompute icon.png

Did you notice how a blue checkmark appears next to the FeaturePython object in the tree view? That is because when an object is created or changed, it is "touched" and needs to be recomputed. Pressing the Std Refresh button will accomplish this.

we can also do this automatically by adding the following line at the end of the create() method:

App.ActiveDocument.recompute()

Be careful where you recompute a FeaturePython object! Generally you should not try to recompute an object from within itself. If possible document recomputing should rather be handled by a method external to the object.

Now, test your changes as follows:

  • Save your changes and return to FreeCAD.
  • Delete any existing objects and reload your module.
  • Finally, create another box object from the Python console by calling box.create('myBox').

Once the box is created and you've checked to make sure it's been recomputed, select the object and look at its properties. You should note two things:

  • Three new properties: Height, Length and Width.
  • A new property group: Dimensions.

Note also how the properties have units. More specifically, they take on the linear units set in the user preferences (Edit → Preference... → General → Units).

No doubt you noticed that three different values were entered for the dimensions: a floating-point value (10.0) and two different strings ('10 mm' and '1 cm'). Yet, all three values are finally converted to the unit specified in the user preferences (mm in the image). The App::PropertyLength type assumes floating-point values are in millimeters, string values are parsed according to the units specified. This built-in behavior makes the App::PropertyLength type ideal for dimensions.

top

Event Trapping

The last element required for a basic FeaturePython object is event trapping. Specifically, we need to trap the execute() event, which is called when the object is recomputed. There are several other document-level events that can be trapped, both in the FeaturePython object itself and in the ViewProvider, which we'll cover in another section.

Add the following after the __init__() function:

def execute(self, obj):
    """
    Called on document recompute
    """

    print('Recomputing {0:s} ({1:s})'.format(obj.Name, self.Type))

Test the code as follows:

  • Save changes and reload the box module in the FreeCAD Python console.
  • Delete any objects in the Tree view
  • Re-create the box object.

You should see the printed output in the Python Console, thanks to the recompute() call we added to the create() method.

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

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

top

The Completed Code

import FreeCAD as App
 
 def create(obj_name):
    """
    Object creation method
    """
 
    obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name))
 
    fpo = box(obj)
 
    return obj
 
 class box():
 
    def __init__(self, obj):
        """
        Default Constructor
        """
 
        self.Type = 'box'
 
       obj.addProperty('App::PropertyString', 'Description', 'Base', 'Box description').Description = ""
       obj.addProperty('App::PropertyLength', 'Length', 'Dimensions', 'Box length').Length = 10.0
       obj.addProperty('App::PropertyLength', 'Width', 'Dimensions', 'Box width').Width = '10 mm'
       obj.addProperty('App::PropertyLength', 'Height', 'Dimensions', 'Box height').Height = '1 cm'
 
        obj.Proxy = self
 
    def execute(self, obj):
        """
        Called on document recompute
        """
 
        print('Recomputing {0:s} {1:s}'.format(obj.Name, self.Type))