Difference between revisions of "FeaturePython Objects/it"

From FreeCAD Documentation
Jump to navigation Jump to search
(Created page with "Category:Python Code/it")
(Updating to match new version of source page)
 
(6 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
<languages/>
 
<languages/>
  
{{docnav/it|[[PySide/it|PySide]]|[[Creating a FeaturePython Box, Part II/it|Creare un Box FeaturePython, Parte II]]}}
+
{{TOCright}}
  
== Introduction ==
+
==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.
+
FeaturePython objects (also referred to as [[Scripted objects]]) provide the ability to extend FreeCAD with objects that integrate seamlessly into the FreeCAD framework.
  
 
This encourages:
 
This encourages:
*'''Rapid prototyping''' of new objects and tools with custom Python classes.
+
*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.
+
*Saving and restoring data (also known as serialization) through {{incode|App::Property}} objects, without embedding any script in the FreeCAD document file.
*'''Creative freedom''' to adapt FreeCAD for any task!
+
*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.
+
On this page we are going to construct a working example of a FeaturePython custom class, identifying all the major components and gaining an understanding of how everything works as we go along.
  
=== How Does It Work? ===
+
==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.
+
FreeCAD comes with a number of default object types for managing different kinds of geometry. Some of them have "FeaturePython" alternatives that allow for customization with a user defined 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.
+
This custom Python class takes a reference to one of these objects and modifies it. For example, the Python class may add properties to the object 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.
  
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 [https://www.howtogeek.com/171993/macros-explained-why-microsoft-office-files-can-be-dangerous/ embedding VBA macros in Microsoft Office documents].
+
When working with custom classes and FeaturePython objects it is important to know that the custom class and its 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. Only the FeaturePython object itself is saved (serialized). But since the script module path is stored in the document, a user need only install the custom Python class code as an importable module, following the same folder structure, to regain the lost functionality.
  
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.
+
[[#top|top]]
  
 +
==Setting things up==
  
== Setting up your development environment ==
+
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.
  
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!
+
If you don't know where the FreeCAD Macro folder is type {{incode|FreeCAD.getUserMacroDir(True)}} in FreeCAD's [[Python console]]:
 +
* On Linux it is usually {{FileName|/home/<username>/.FreeCAD/Macro/}}.
 +
* On Windows it is {{FileName|%APPDATA%\FreeCAD\Macro\}}, which is usually {{FileName|C:\Users\<username>\Appdata\Roaming\FreeCAD\Macro\}}.
 +
* On Mac OSX it is usually {{FileName|/Users/<username>/Library/Preferences/FreeCAD/Macro/}}.
  
If you don't know where the FreeCAD Macro folder is type 'FreeCAD.getUserMacroDir(True)' in FreeCAD's Python console. The place is configurable but, by default, to go there:
+
Now we need to create some folders and files:
*Windows: Type '%APPDATA%/FreeCAD/Macro' in the filepath bar at the top of Explorer
+
*In the {{FileName|Macro}} folder create a new folder called {{FileName|fpo}}.  
*Linux: Navigate to /home/USERNAME/.FreeCAD/Macro
+
*In the {{FileName|fpo}} folder create an empty file: {{FileName|__init__.py}}.
*Mac: Navigate to /Users/USERNAME/Library/Preferences/FreeCAD/Macro
+
*In the {{FileName|fpo}} folder, create a  new folder called {{FileName|box}}.
 +
*In the {{FileName|box}} folder create two files: {{FileName|__init__.py}} and {{FileName|box.py}} (leave both empty for now).
  
Now we need to create some files.
+
Your folder structure should look like this:
*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)
 
  
Notes:
+
Macro/
* 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.
+
    |--> fpo/
* '''__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.
+
        |--> __init__.py
 +
        |--> box/
 +
            |--> __init__.py
 +
            |--> box.py
  
Your directory structure should look like this:
+
The {{FileName|fpo}} folder provides a nice place to play with new FeaturePython objects and the {{FileName|box}} folder is the module we will be working in. {{FileName|__init__.py}} tells Python that there is an importable module in the folder, and {{FileName|box.py}} will be the class file for our new FeaturePython Object.
  
.FreeCAD
+
With our module paths and files created, let's make sure FreeCAD is set up properly:
  |--> Macro
+
*Start FreeCAD (if you haven't done so already).
        |--> fpo
+
*Enable the [[Report view]] ({{MenuCommand|View → Panels → Report view}}).
            |--> __init__.py
+
*Enable the [[Python console]] ({{MenuCommand|View → Panels → Python console}}) see [[FreeCAD Scripting Basics]].
            |--> box
 
                  |--> __init__.py
 
                  |--> box.py
 
  
With our module paths and files created, let's make sure FreeCAD is set up properly:
+
Finally, navigate to the {{FileName|Macro/fpo/box}} folder and open {{FileName|box.py}} in your favorite code editor. We will only edit that file.
  
*Start FreeCAD (if it isn't already open)
+
[[#top|top]]
*Enable Python Console and Report Views ('''View -> Panels -> Report view''' and '''Python console''') [[FreeCAD Scripting Basics|(learn more about it here)]]
 
*In your favorite code editor, navigate to the '''/Macro/fpo/box''' folder and open '''box.py'''
 
  
It's time to write some code!
+
==A FeaturePython object==
  
 +
Let's get started by writing our class and its constructor:
  
-----
+
{{Code|code=
 +
class box():
  
== A Very Basic FeaturePython Object ==
+
    def __init__(self, obj):
 +
        """
 +
        Default constructor
 +
        """
  
Let's get started by writing our class and it's constructor:
+
        self.Type = 'box'
  
  class box():
+
        obj.Proxy = self
   
+
}}
      def __init__(self, obj):
 
          """
 
          Constructor
 
         
 
          Arguments
 
          ---------
 
          - obj: a variable created with FreeCAD.Document.addObject('App::FeaturePython', '{name}').
 
          """
 
          self.Type = 'box'
 
   
 
          obj.Proxy = self
 
  
 +
'''The {{incode|__init__()}} method breakdown:'''
  
'''The <code>__init__()</code> method breakdown'''
+
{|class="wikitable" cellpadding="5px" width="100%"
{|class="wikitable" cellpadding="5" style="margin-left: 15px; margin-right: 5px"
+
|style="width:25%" | {{incode|def __init__(self, obj):}}
|style="width:30%" | <code>def __init__(self, obj):</code> || Parameters refer to the Python class itself and the FeaturePython object that it is attached to.
+
|style="width:75%" | Parameters refer to the Python class itself and the FeaturePython object that it is attached to.
 
|-
 
|-
|<code>    self.Type = 'box'</code> || String definition of the custom python type
+
| {{incode|self.Type <nowiki>=</nowiki> 'box'}}
 +
| String definition of the custom Python type.
 
|-
 
|-
|<code>    obj.Proxy = self</code> || Stores a reference to the Python instance in the FeaturePython object
+
| {{incode|obj.Proxy <nowiki>=</nowiki> self}}
 +
| Stores a reference to the Python instance in the FeaturePython object.
 
|}
 
|}
  
 +
Add the following code at the top of the file:
 +
 +
{{Code|code=
 +
import FreeCAD as App
 +
 +
def create(obj_name):
 +
    """
 +
    Object creation method
 +
    """
 +
 +
    obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)
  
In the '''box.py''' file at the top, add the following code:
+
    box(obj)
  
  import FreeCAD as App
+
    return obj
+
}}
  def create(obj_name):
 
      """
 
      Object creation method
 
      """
 
 
      obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)
 
 
      fpo = box(obj)
 
 
      return fpo
 
  
 +
'''The {{incode|create()}} method breakdown:'''
  
'''The <code>create()</code> method breakdown'''
+
{|class="wikitable" cellpadding="5px" width="100%"
{|class="wikitable" cellpadding="5" style="float:right; margin-left: 15px; margin-right: 5px"
+
|style="width:25%" | {{incode|import FreeCAD as App}}
|style="width:30%" | <code>import FreeCAD as App</code> || Standard import for most python scripts.  The '''App''' alias is not required.
+
|style="width:75%" | Standard import for most Python scripts, the App alias is not required.
 +
|-
 +
| {{incode|obj <nowiki>=</nowiki> ... 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. Otherwise, a unique name and label will be created based on 'obj_name'.
 
|-
 
|-
|<code>obj = ... addObject(...)</code> || 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'.
+
| {{incode|box(obj)}}
 +
| Creates our custom class instance.
 
|-
 
|-
|<code>fpo = box(obj)</code> || Create our custom class instance and link it to the FeaturePython object.
+
| {{incode|return obj}}
 +
| Returns the FeaturePython object.
 
|}
 
|}
  
 +
The {{incode|create()}} method is not required, but it provides a nice way to encapsulate the object creation code.
  
The <code>create()</code> method is not required, but it provides a nice way to encapsulate the object creation code.
+
[[#top|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 {{KEY|Ctrl}}+{{KEY|N}} or selecting {{MenuCommand|File → New}}.
  
=== Testing the Code ===
+
In the Python console type the following:
  
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'''
+
{{Code|code=
 +
from fpo.box import box
 +
}}
  
In the Python Console, type the following:
+
Now we need to create our object:
  
>>> from fpo.box import box
+
{{Code|code=
 +
mybox = box.create('my_box')
 +
}}
  
<br>Now, we need to create our object:
+
[[Image:Fpo_treeview.png | right]]
 +
You should see a new object appear in the [[Tree_view|Tree view]] labelled "my_box".
  
>>> box.create('my_box')
+
Note that the icon is gray. FreeCAD is telling us that the object is not able to display anything in the [[3D_view|3D view]]. Click on the object and look at its properties in the [[Property_editor|Property editor]]. There is not much there, just the name of the object.
  
[[File:Fpo_treeview.png | right | 192px]]
+
Also note that there is a small blue check mark 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 {{Button|[[Image:Std_Refresh.svg|16px]] [[Std_Refresh|Std Refresh]]}} button will accomplish this. We will add some code to automate this later.
You should see a new object appear in the tree view at the top left labelled '''my_box'''.<br><br>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.<br>There's not very much - just the name of the object. We'll need to add some properties in a bit.
+
{{Clear}}
<br clear="all">
 
Let's also make referencing our new object a little more convenient:
 
  
>>> mybox = App.ActiveDocument.my_box
+
Let's look at our object's attributes:
 +
{{Code|code=
 +
dir(mybox)
 +
}}
  
And then we should take a look at our object's attributes:
+
This will return:
  
>>> dir(mybox)
+
{{Code|code=
['Content', 'Document', 'ExpressionEngine', 'InList', 'InListRecursive', 'Label', 'MemSize', 'Module', 'Name', 'OutList', 'OutListRecursive', 'PropertiesList', 'Proxy', 'State', 'TypeId', 'ViewObject', '__class__',  
+
['Content', 'Document', 'ExpressionEngine', 'FullName', 'ID', 'InList',
  ...
+
...
  'setEditorMode', 'setExpression', 'supportedProperties', 'touch']
+
'setPropertyStatus', 'supportedProperties', 'touch']
 +
}}
  
 +
There are a lot of attributes because we're accessing the native FreeCAD FeaturePyton object created in the first line of our {{incode|create()}} method. The {{incode|Proxy}} property we added in our {{incode|__init__()}} method is there too.
  
There's a lot of attributes there because we're accessing the native FreeCAD FeaturePyton object that we created in the first line of our <code>create()</code> method.
+
Let's inspect it with the {{incode|dir()}} method:
The <code>Proxy</code> property we added in our <code>__init__()</code> method is there, too.
 
  
Let's inspect that by calling the <code>dir()</code>on the Proxy object:
+
{{Code|code=
 +
dir(mybox.Proxy)
 +
}}
  
>>> dir(mybox.Proxy)
+
This will return:
['Object', 'Type', '__class__', '__delattr__', '__dict__', '__dir__',
 
  ...
 
  '__str__', '__subclasshook__', '__weakref__']
 
  
 +
{{Code|code=
 +
['Type', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
 +
...
 +
'__str__', '__subclasshook__', '__weakref__']
 +
}}
  
Once we inspect the Proxy property, we can see our <code>Object</code> and <code>Type</code> properties.  This means we're accessing the custom Python object defined in  '''box.py'''.
+
We can see our {{incode|Type}} property. Let's check it:
  
Call the <code>Type</code> property and look at the result:
+
{{Code|code=
>>> mybox.Proxy.Type
+
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.
+
This will return:
  
Likewise, we can access the FreeCAD object (not our Python object) by using the<code>Object</code>method:
+
{{Code|code=
>>> mybox.Proxy.Object
+
'box'
 +
}}
  
That was fun!  But now let's see if we can make our class a little more interesting... and maybe more useful.
+
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 as well.
  
-----
+
[[#top|top]]
  
=== Adding Properties ===
+
===Adding properties===
  
Properties are the lifeblood of a FeaturePython class.
+
Properties are the lifeblood of a FeaturePython class. Fortunately, FreeCAD supports [[FeaturePython_Custom_Properties|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. To avoid having to serialize data yourself, it is advisable to only use these property types.
<br><br>Fortunately, FreeCAD supports [[FeaturePython_Custom_Properties|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.
 
<br><br>Adding properties is done quite simply using the <code>add_property()</code> method. The syntax for the method is:
 
  
 +
Adding properties is done using the {{incode|add_property()}} method. The syntax for the method is:
 +
 +
<!--Do not use Code template to avoid syntax highlighting-->
 
  add_property(type, name, section, description)
 
  add_property(type, name, section, description)
  
{|class="wikitable" cellpadding="5" style="float:right; margin-left: 15px; margin-right: 5px; text-align:left"
+
You can view the list of supported properties by typing:
!Tip
+
 
|-
+
{{Code|code=
||You can view the list of supported properties for an object by typing:<br><code>>>> mybox.supportedProperties()</code>
+
mybox.supportedProperties()
|}
+
}}
<br>Let's try adding a property to our box class.
+
 
<br><br>Switch to your code editor and move to the <code>__init__()</code> method.
+
Let's try adding a property to our box class. Switch to your code editor, move to the {{incode|__init__()}} method, and at the end of the method add:
 +
 
 +
{{Code|code=
 +
obj.addProperty('App::PropertyString', 'Description', 'Base', 'Box description').Description = ""
 +
}}
 +
 
 +
Note how we're using the reference to the (serializable) FeaturePython object {{incode|obj}}, and not the (non-serializable) Python class instance {{incode|self}}.
 +
 
 +
Once you're done, save the changes and switch back to FreeCAD. Before we can observe the changes made to our code, we need to reload the module. This can be accomplished by restarting FreeCAD, but restarting FreeCAD every time we edit the code would be inconvenient. To make things easier type the following in the Python console:
 +
 
 +
{{Code|code=
 +
from importlib import reload
 +
reload(box)
 +
}}
 +
 
 +
With the module reloaded, let's see what we get when we create an object:
 +
 
 +
{{Code|code=
 +
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 on the left and the tooltip should appear with the description 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.
 +
 
 +
[[#top|top]]
 +
 
 +
Let's add some more properties. Return to your source code and add the following properties to the {{incode|__init__()}} method:
 +
 
 +
{{Code|code=
 +
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'
 +
}}
 +
 
 +
And let's also add some code to recompute the document automatically. Add the following line above the {{incode|return()}} statement in the {{incode|create()}} method :
  
<br clear="all">Then, at the end of the method, add:
+
{{Code|code=
 +
App.ActiveDocument.recompute()
 +
}}
  
obj.addProperty('App::PropertyString', 'Description', 'Base', 'Box description').Description = ""
+
'''Be careful where you recompute a FeaturePython object. Recomputing should be handled by a method external to its class.'''
Note how we're using the reference to the (serializable) FeaturePython object, <code>obj</code> and not the (non-serializable) Python class instanace, <code>self</code>.
 
<br>Anyway, once you're done, save the changes and switch back to FreeCAD.
 
<br><br>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
+
[[Image:fpo_box_properties.png | right]]
>>> reload(box)
 
This will reload the box module, incorporating changes you made to the '''box.py''' file, just as if you'd restarted FreeCAD.
 
<br><br>With the module reloaded, now let's see what we get when we create an object:
 
  
>>> box.create('box_property_test')
+
Now, test your changes as follows:
[[File:fpo_properties.png | right | 320px]]You should see the new box object appear in the tree view at left.<br><br>
+
*Save your changes and reload your module.
*Select it and look at the Property Panel. There, you should see the 'Description' property.<br>
+
*Delete all objects in the Tree view.
*Hover over the property name at left and see the tooltip appear with the description text you provided.<br>
+
*Create a new box object from the Python console by calling {{incode|box.create('myBox')}}.
*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.
 
<br><br>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''.
 
<br><br>Return to your source code and add the following properties to <code>__init__()</code>:
 
  
obj.addProperty('App::PropertyLength', 'Length', 'Dimensions', 'Box length').Length = 10.0
+
Once the box is created and you've checked to make sure it has been recomputed, select the object and look at its properties. You should note two things:
obj.addProperty('App::PropertyLength', 'Width', 'Dimensions', 'Box width').Width = '10 mm'
+
*A new property group: ''Dimensions''.
obj.addProperty('App::PropertyLength', 'Height', 'Dimensions', 'Box height').Height = '1 cm'
+
*Three new properties: ''Height'', ''Length'' and ''Width''.
  
[[File:object_recompute_icon.png | left | 64px]]One last thing:  Did you notice how the blue checkmark appears next to the FeaturePython object in the treeview at left?
+
Note also how the properties have units. More specifically, they have taken on the linear units set in the user preferences ({{MenuCommand|Edit → Preference... → General → Units}}).
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.
+
{{Clear}}
<br><br>But, we can accomplish that automatically by adding the following line to the end of the <code>create()</code> method:
 
  
App.ActiveDocument.recompute()
+
No doubt you noticed that three different values were entered for the dimensions: a floating-point value ({{incode|10.0}}) and two different strings ({{incode|'10 mm'}} and {{incode|'1 cm'}}). The {{incode|App::PropertyLength}} type assumes floating-point values are in millimeters, string values are parsed according to the units specified, and in the GUI all values are converted to the units specified in the user preferences ({{incode|mm}} in the image). This built-in behavior makes the {{incode|App::PropertyLength}} type ideal for dimensions.
{|class="wikitable" cellpadding="5" style="margin-left: 15px; margin-right: 15px; text-align:left"
 
!Note
 
|-
 
|Be careful where you recompute a FeaturePython object!  Generally, you should not try to recompute an object from within itself.  Rather, document recomputing should be handled by a method external to the object, if possible.
 
|}
 
<br>Now, test your changes as follows:<br>
 
*Save your changes and return to FreeCAD.<br>
 
*Delete any existing objects and reload your module.<br>
 
*Finally, create another box object from the command line by calling <code>>>> box.create('myBox')</code>.
 
[[File:fpo_box_properties.png | right | 320px]]
 
<br>Once the box is created (and you've checked to make sure it's been recomputed!), select the object and look at your properties. 
 
<br>You should note two things:<br>
 
*Three new properties (''length'', ''width'', and ''height'')
 
*A new property group, ''Dimensions''.
 
<br>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''').
 
<br clear="all"><br>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.
 
<br><br>The nice thing about the <code>App::PropertyLength</code> 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 <code>App::PropertyLength</code> as the property type.
 
  
 +
[[#top|top]]
  
-----
+
===Trapping events===
  
=== Event Trapping ===
+
The last element required for a basic FeaturePython object is event trapping. A FeaturePython object can react to events with callback functions. In our case we want the object to react whenever it is recomputed. In other words we want to trap recomputes. To accomplish this we need to add a function with a specific name, {{incode|execute()}}, to the object class. There are several other events that can be trapped, both in the FeaturePython object itself and in the [[Viewprovider|ViewProvider]], which we'll cover in the [[Creating_a_FeaturePython_Box,_Part_II|next section]].
  
The last element required for a basic FeaturePython object is event trapping.  Specifically, we need to trap the <code>execute()</code> 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.
+
For a complete reference of methods available to implement on FeautrePython classes, see [[FeaturePython methods]].
<br>
 
Add the following after the <code>__init__()</code> function:
 
  
def execute(self, obj):
+
Add the following after the {{incode|__init__()}} function:
    """
 
    Called on document recompute
 
    """
 
 
    print('Recomputing {0:s} ({1:s})'.format(obj.Name, self.Type))
 
  
 +
{{Code|code=
 +
def execute(self, obj):
 +
    """
 +
    Called on document recompute
 +
    """
  
Test the code  as follows:
+
    print('Recomputing {0:s} ({1:s})'.format(obj.Name, self.Type))
*Save changes and reload the box module in the FreeCAD python console.
+
}}
*Delete any objects in the Treeview
 
*Re-create the box object.
 
  
You should see the printed output in the Python Console, thanks to the <code>recompute()</code> call we added to the <code>create()</code> method.
+
Test the code by again following these steps:
 +
*Save and reload the module.
 +
*Delete all objects.
 +
*Create a new box object.
  
Of course, the <code>execute()</code> method doesn't do anything here (except tell us that it was called), but it is the key to the magic of FeaturePython objects.
+
You should see the printed output in the Python Console, thanks to the {{incode|recompute()}} call we added to the {{incode|create()}} method. Of course, the {{incode|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.
  
<br>'''So that's it!'''
+
That's it, you now know how to build a basic, functional FeaturePython object!
<br>You now know how to build a basic, functional FeaturePython object!
 
  
 +
[[#top|top]]
  
-----
+
===Complete code===
  
=== The Completed Code ===
+
{{Code|code=
import FreeCAD as App
+
import FreeCAD as App
+
 
def create(obj_name):
+
def create(obj_name):
 
     """
 
     """
 
     Object creation method
 
     Object creation method
 
     """
 
     """
+
 
     obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name))
+
     obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)
+
 
     fpo = box(obj)
+
     box(obj)
+
 
     return fpo
+
    App.ActiveDocument.recompute()
+
 
class box():
+
     return obj
+
 
 +
class box():
 +
 
 
     def __init__(self, obj):
 
     def __init__(self, obj):
 
         """
 
         """
         Default Constructor
+
         Default constructor
 
         """
 
         """
+
 
 
         self.Type = 'box'
 
         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
 
         obj.Proxy = self
+
 
 +
        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'
 +
 
 
     def execute(self, obj):
 
     def execute(self, obj):
 
         """
 
         """
 
         Called on document recompute
 
         Called on document recompute
 
         """
 
         """
 
        print('Recomputing {0:s} {1:s}'.format(obj.Name, self.Type))
 
{{docnav|PySide|Creating a FeaturePython Box, Part II}}
 
  
{{Userdocnavi/it}}
+
        print('Recomputing {0:s} ({1:s})'.format(obj.Name, self.Type))
 +
}}
  
[[Category:Poweruser Documentation/it]]
+
[[#top|top]]
  
[[Category:Python Code/it]]
+
{{Powerdocnavi{{#translation:}}}}
 +
[[Category:Developer Documentation{{#translation:}}]]
 +
[[Category:Python Code{{#translation:}}]]
 +
{{clear}}

Latest revision as of 21:00, 23 August 2020

Other languages:
Deutsch • ‎English • ‎français • ‎italiano • ‎русский

Introduction

FeaturePython objects (also referred to as Scripted objects) provide 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.
  • Saving and restoring data (also known as serialization) through App::Property objects, without embedding any script in the FreeCAD document file.
  • Creative freedom to adapt FreeCAD for any task.

On this page we are going to construct a working example of a FeaturePython custom class, identifying all the major components and gaining an understanding of how everything works as we go along.

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 customization with a user defined Python class.

This custom Python class takes a reference to one of these objects and modifies it. For example, the Python class may add properties to the object 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 the custom class and its 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. Only the FeaturePython object itself is saved (serialized). But since the script module path is stored in the document, a user need only install the custom Python class code as an importable module, following the same folder 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 folders and 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 folder 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. We will only edit that file.

top

A FeaturePython object

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

class box():

    def __init__(self, obj):
        """
        Default constructor
        """

        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.

Add the following code at the top of the file:

import FreeCAD as App

def create(obj_name):
    """
    Object creation method
    """

    obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)

    box(obj)

    return obj

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. Otherwise, a unique name and label will be created based on 'obj_name'.
box(obj) Creates our custom class instance.
return obj Returns 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:

mybox = box.create('my_box')
Fpo treeview.png

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 is not able to display anything in the 3D view. Click on the object and look at its properties in the Property editor. There is not much there, just the name of the object.

Also note that there is a small blue check mark 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.svg Std Refresh button will accomplish this. We will add some code to automate this later.


Let's look at our object's attributes:

dir(mybox)

This will return:

['Content', 'Document', 'ExpressionEngine', 'FullName', 'ID', 'InList',
...
'setPropertyStatus', '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 as well.

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. To avoid having to serialize data yourself, it is advisable to only use these property types.

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 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 made to our code, we need to reload the module. This can be accomplished by restarting FreeCAD, but restarting FreeCAD every time we edit the code would be inconvenient. To make things easier type the following in the Python console:

from importlib import reload
reload(box)

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 on the left and the tooltip should appear with the description 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.

top

Let's add some more properties. 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'

And let's also add some code to recompute the document automatically. Add the following line above the return() statement in the create() method :

App.ActiveDocument.recompute()

Be careful where you recompute a FeaturePython object. Recomputing should be handled by a method external to its class.

Fpo box properties.png

Now, test your changes as follows:

  • Save your changes and reload your module.
  • Delete all objects in the Tree view.
  • Create a new box object from the Python console by calling box.create('myBox').

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

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

Note also how the properties have units. More specifically, they have taken 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'). The App::PropertyLength type assumes floating-point values are in millimeters, string values are parsed according to the units specified, and in the GUI all values are converted to the units specified in the user preferences (mm in the image). This built-in behavior makes the App::PropertyLength type ideal for dimensions.

top

Trapping events

The last element required for a basic FeaturePython object is event trapping. A FeaturePython object can react to events with callback functions. In our case we want the object to react whenever it is recomputed. In other words we want to trap recomputes. To accomplish this we need to add a function with a specific name, execute(), to the object class. There are several other events that can be trapped, both in the FeaturePython object itself and in the ViewProvider, which we'll cover in the next section.

For a complete reference of methods available to implement on FeautrePython classes, see FeaturePython methods.

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 by again following these steps:

  • Save and reload the module.
  • Delete all objects.
  • Create a new 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

Complete code

import FreeCAD as App

def create(obj_name):
    """
    Object creation method
    """

    obj = App.ActiveDocument.addObject('App::FeaturePython', obj_name)

    box(obj)

    App.ActiveDocument.recompute()

    return obj

class box():

    def __init__(self, obj):
        """
        Default constructor
        """

        self.Type = 'box'

        obj.Proxy = self

        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'

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

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

top