PyFlow.Core package

Submodules

PyFlow.Core.Common module

class PyFlow.Core.Common.AccessLevel

Bases: enum.IntEnum

Can be used for code generation

private = 1

private

protected = 2

protected

public = 0

public

class PyFlow.Core.Common.DictElement

Bases: tuple

PyFlow dict element class

This subclass of python’s tuple is to represent dict elements to construct typed dicts

class PyFlow.Core.Common.Direction

Bases: enum.IntEnum

Direction identifiers

Down = 3

Down

Left = 0

Left

Right = 1

Right

Up = 2

Up

PyFlow.Core.Common.GetRangePct(MinValue, MaxValue, Value)

Calculates the percentage along a line from MinValue to MaxValue that value is.

Parameters:
  • MinValue – Minimum Value
  • MaxValue – Maximum Value
  • Value – Input value
Returns:

The percentage (from 0.0 to 1.0) betwen the two values where input value is

class PyFlow.Core.Common.NodeMeta

Bases: object

Node meta constants

Variables:
  • CATEGORY – To specify category for node. Will be considered by node box
  • KEYWORDS – To specify list of additional keywords, used in node box search field
  • CACHE_ENABLED – To specify if node is cached or not
class PyFlow.Core.Common.NodeTypes

Bases: enum.IntEnum

Determines whether it is callable node or pure

Callable = 0

Callable node is a node with exec pins

Pure = 1

Normal nodes

class PyFlow.Core.Common.PFDict(keyType, valueType=None, inp={})

Bases: dict

This subclass of python’s dict implements a key typed dictionary.

Only defined data types can be used as keys, and only hashable ones as determined by

>>> isinstance(dataType, collections.Hashable)

To make a Class Hashable some methods should be implemented:

Example:

class C:
    def __init__(self, x):
        self.x = x
    def __repr__(self):
        return "C({})".format(self.x)
    def __hash__(self):
        return hash(self.x)
    def __eq__(self, other):
        return (self.__class__ == other.__class__ and self.x == other.x)
__init__(keyType, valueType=None, inp={})
Parameters:
  • keyType – Key dataType
  • valueType (optional) – value dataType, defaults to None
  • inp (dict, optional) – Construct from another dict, defaults to {}
getClassFromType(pinType)

Gets the internal data structure for a defined pin type

Parameters:pinType (class or None) – pinType Name
class PyFlow.Core.Common.PinDirection

Bases: enum.IntEnum

Determines whether it is input pin or output

Input = 0

Left side pins

Output = 1

Right side pins

class PyFlow.Core.Common.PinOptions

Bases: enum.Flag

Used to determine how Pin behaves.

Apply flags on pin instances.

AllowAny = 512

Special flag that allow a pin to be AnyPin, which means non typed without been marked as error. By default a PyFlow.Packages.PyFlowBase.Pins.AnyPin.AnyPin need to be initialized with some data type, other defined pin. This flag overrides that. Used in lists and non typed nodes

AllowMultipleConnections = 8

This enables pin to allow more that one input connection. See connectPins()

AlwaysPushDirty = 128

Pin will always be seen as dirty (computation needed)

ArraySupported = 1

Pin can hold array data structure

ChangeTypeOnConnection = 16

Used by AnyPin to determine if it can change its data type on new connection.

DictElementSupported = 1024

Dicts are constructed with DictElement objects. So dict pins will only allow other dicts until this flag enabled. Used in makeDict node

DictSupported = 2

Pin can hold dict data structure

Dynamic = 64

Specifies if pin was created dynamically (during program runtime)

RenamingEnabled = 32

Determines if pin can be renamed

Storable = 256

Determines if pin data can be stored when pin serialized

SupportsOnlyArrays = 4

Pin will only support other pins with array data structure

class PyFlow.Core.Common.PinReconnectionPolicy

Bases: enum.IntEnum

How to behave if pin has connections and another connection about to be performed.

DisconnectIfHasConnections = 0

Current connection will be broken

ForbidConnection = 1

New connection will be cancelled

class PyFlow.Core.Common.PinSelectionGroup

Bases: enum.IntEnum

Used in getPinSG() for optimization purposes

BothSides = 2

Both sides pins

Inputs = 0

Input pins

Outputs = 1

Outputs pins

class PyFlow.Core.Common.PinSpecifires

Bases: object

Pin specifires constants

Variables:
  • SUPPORTED_DATA_TYPES – To specify supported data types list
  • CONSTRAINT – To specify type constraint key
  • STRUCT_CONSTRAINT – To specify struct constraint key
  • ENABLED_OPTIONS – To enable options
  • DISABLED_OPTIONS – To disable options
  • INPUT_WIDGET_VARIANT – To specify widget variant string
  • DESCRIPTION – To specify description for pin, which will be used as tooltip
  • VALUE_LIST – Specific for string pin. If specified, combo box will be created
  • VALUE_RANGE – Specific for ints and floats. If specified, slider will be created instead of value box
  • DRAGGER_STEPS – To specify custom value dragger steps
class PyFlow.Core.Common.SingletonDecorator(cls)

Bases: object

Decorator to make class unique, so each time called same object returned

__init__(cls)

Initialize self. See help(type(self)) for accurate signature.

class PyFlow.Core.Common.StructureType

Bases: enum.IntEnum

Used to determine structure type for values.

Array = 1

Python list structure, represented as arrays -> typed and lists -> non typed

Dict = 2

PFDict structure, is basically a rey typed python dict

Multi = 3

This means it can became any of the previous ones on connection/user action

Single = 0

Single data structure

PyFlow.Core.Common.arePinsConnected(src, dst)

Checks if two pins are connected

Note

Pins can be passed in any order if src pin is PyFlow.Core.Common.PinDirection, they will be swapped

Parameters:
Returns:

True if Pins are connected

Return type:

bool

PyFlow.Core.Common.canConnectPins(src, dst)

Very important fundamental function, it checks if connection between two pins is possible

Parameters:
Returns:

True if connection can be made, and False if connection is not possible

Return type:

bool

PyFlow.Core.Common.clamp(n, vmin, vmax)

Computes the value of the first specified argument clamped to a range defined by the second and third specified arguments

Parameters:
  • n – input Value
  • vmin – MiniMum Value
  • vmax – Maximum Value
Returns:

The clamped value of n

PyFlow.Core.Common.clearList(list)

Clears python list

Parameters:list (list) – list to clear
Returns:cleared List
Return type:list
PyFlow.Core.Common.clearSignal(signal)

Disconnects all receivers

Parameters:signal (Signal) – emitter
PyFlow.Core.Common.connectPins(src, dst)

Connects two pins

This are the rules how pins connect:

Parameters:
Returns:

True if connected Successfully

Return type:

bool

PyFlow.Core.Common.connectPinsByIndexes(lhsNode=None, lhsOutPinIndex=0, rhsNode=None, rhsInPinIndex=0)

Connects pins regardless name.

This function uses pin locations on node. Top most pin have position index 1, pin below - 2 etc.

Parameters:
  • lhsNode (NodeBase) – Left hand side node
  • lhsOutPinIndex (int) – Out pin position on left hand side node
  • rhsNode (NodeBase) – Right hand side node
  • rhsInPinIndex (int) – Out pin position on right hand side node
PyFlow.Core.Common.cycleCheck(src, dst)

Check for cycle connected nodes

Parameters:
Returns:

True if cycle deleted

Return type:

bool

PyFlow.Core.Common.disconnectPins(src, dst)

Disconnects two pins

Parameters:
  • src (PinBase) – left hand side pin
  • dst (PinBase) – right hand side pin
Returns:

True if disconnection success

Return type:

bool

PyFlow.Core.Common.extractDigitsFromEndOfString(string)

Get digits at end of a string

Example:

>>> nums = extractDigitsFromEndOfString("h3ello154")
>>> print(nums, type(nums))
>>> 154 <class 'int'>
Parameters:string (str) – Input numbered string
Returns:Numbers in the final of the string
Return type:int
PyFlow.Core.Common.findGoodId(ids)

Finds good minimum unique int from iterable. Starting from 1

Parameters:ids (list|set|tuple) – a collection of occupied ids
Returns:Unique Id
Return type:int
PyFlow.Core.Common.findStructFromValue(value)

Finds StructureType from value

Parameters:value – input value to find structure.
Returns:Structure Type for input value
Return type:StructureType
PyFlow.Core.Common.getConnectedPins(pin)

Find all connected Pins to input Pin

Parameters:pin (PyFlow.Core.PinBase.PinBase) – Pin to search connected pins
Returns:Set of connected pins
Return type:set(PyFlow.Core.PinBase.PinBase)
PyFlow.Core.Common.getUniqNameFromList(existingNames, name)

Create unique name

Iterates over existingNames and extracts the end digits to find a new unique id

Parameters:
  • existingNames (list) – List of strings where to search for existing indexes
  • name (str) – Name to obtain a unique version from
Returns:

New name non overlapin with any in existingNames

Return type:

str

PyFlow.Core.Common.lerp(start, end, alpha)

Performs a linear interpolation

>>> start + alpha * (end - start)
Parameters:
  • start – start the value to interpolate from
  • end – end the value to interpolate to
  • alpha – alpha how far to interpolate
Returns:

The result of the linear interpolation

PyFlow.Core.Common.mapRangeClamped(Value, InRangeA, InRangeB, OutRangeA, OutRangeB)

Returns Value mapped from one range into another where the Value is clamped to the Input Range. (e.g. 0.5 normalized from the range 0->1 to 0->50 would result in 25)

PyFlow.Core.Common.mapRangeUnclamped(Value, InRangeA, InRangeB, OutRangeA, OutRangeB)

Returns Value mapped from one range into another where the Value is clamped to the Input Range. (e.g. 0.5 normalized from the range 0->1 to 0->50 would result in 25)

PyFlow.Core.Common.pinAffects(lhs, rhs)

This function for establish dependencies bitween pins

Warning

Used internally, users will hardly need this

Parameters:
PyFlow.Core.Common.push(start_from)

Marks dirty all ports from start to the right

this part of graph will be recomputed every tick

Parameters:start_from (PinBase) – pin from which recursion begins
PyFlow.Core.Common.removeDigitsFromEndOfString(string)

Delete the numbers at the end of a string

Similar to extractDigitsFromEndOfString(), but removes digits in the end.

Parameters:string (string) – Input string
Returns:Modified string
Return type:string
PyFlow.Core.Common.roundup(x, to)

Rounding up to sertain value

>>> roundup(7, 8)
>>> 8
>>> roundup(8, 8)
>>> 8
>>> roundup(9, 8)
>>> 16
Parameters:
  • x – value to round
  • to – value x will be rounded to
Returns:

rounded value of x

Return type:

int

PyFlow.Core.Common.sign(x)

Returns sign of x. -1 if x is negative, 1 if positive and zero if 0.

>>> x and (1, -1)[x < 0]
PyFlow.Core.Common.traverseConstrainedPins(startFrom, callback)

Iterate over constrained and connected pins

Iterates over all constrained chained pins of type Any and passes pin into callback function. Callback will be executed once for every pin

Parameters:
  • startFrom (PinBase) – First pin to start Iteration
  • callback (callback(PinBase)) – Functor to execute in each iterated pin.
PyFlow.Core.Common.wrapStringToFunctionDef(functionName, scriptString, kwargs=None)

Generates function string which then can be compiled and executed

Example:

wrapStringToFunctionDef('test', 'print(a)', {'a': 5})

Will produce following function:

def test(a=5):
    print(a)

PyFlow.Core.EvaluationEngine module

class PyFlow.Core.EvaluationEngine.DefaultEvaluationEngine_Impl

Bases: PyFlow.Core.Interfaces.IEvaluationEngine

Default evaluation engine implementation

__init__()

Initialize self. See help(type(self)) for accurate signature.

PyFlow.Core.FunctionLibrary module

PyFlow.Core.FunctionLibrary.IMPLEMENT_NODE(func=None, returns={}, meta={}, nodeType=NodeTypes.Pure)

Detailed description

We use this function as decorator in 100% cases. See PyFlow/Packages/PyFlowBase/FunctionLibraries content for plenty of examples

Arguments

func

Function to be annotated

returns

Value of this argument is tuple with 2 or 3 elements or None. First element is pin data type. Second - default value. Third element is pin specifires

meta

Value of this argument is node meta

nodeType

Value of this argument is NodeTypes. If Callable specified input and output exec pins will be created.

Examples:

@IMPLEMENT_NODE(returns=('IntPin', 0), meta={NodeMeta.CATEGORY: 'GenericTypes', NodeMeta.KEYWORDS: []})
def makeInt(i=('IntPin', 0)):
    return i

@IMPLEMENT_NODE(returns=('FloatPin', 0.0, {PinSpecifires.ENABLED_OPTIONS: PinOptions.AlwaysPushDirty}))
def clock():
    return time.clock()
pin specifires

dict that describes different pin options and attributes to be considered on generation

Following key-value pairs allowed:

>>> (PinSpecifires.SUPPORTED_DATA_TYPES : list)
>>> (PinSpecifires.CONSTRAINT: None)
>>> (PinSpecifires.STRUCT_CONSTRAINT: None)
>>> (PinSpecifires.ENABLED_OPTIONS: None)
>>> (PinSpecifires.DISABLED_OPTIONS: None)
>>> (PinSpecifires.INPUT_WIDGET_VARIANT: "DefaultWidget")
>>> (PinSpecifires.DESCRIPTION: str)
>>> (PinSpecifires.VALUE_LIST: [str])
>>> (PinSpecifires.VALUE_RANGE: (int|float, int|float))
>>> (PinSpecifires.DRAGGER_STEPS: [int|float])

Value list is specific for string pins. If Specified - enum input widget will be created for this pin. If value range is specified, slider will be created in property view instead of value box. Dragger steps is a list of values which will be used in value dragger (middle mouse button).

node meta

dict that describes different node options and attributes to be considered on generation

Following key-value pairs allowed:

>>> ("Category" : str)
>>> ("Keywords" : [str])
>>> ("CacheEnabled" : bool)
class PyFlow.Core.FunctionLibrary.FunctionLibraryBase(packageName)

Bases: object

Base class fo function libraries

__init__(packageName)

Initialize self. See help(type(self)) for accurate signature.

PyFlow.Core.GraphBase module

class PyFlow.Core.GraphBase.GraphBase(name, manager, parentGraph=None, category='', uid=None, *args, **kwargs)

Bases: PyFlow.Core.Interfaces.ISerializable

Data structure representing a nodes graph

Variables:
  • graphManager (GraphManager) – reference to graph manager
  • nameChanged (Signal) – signal emitted after graph name was changed
  • categoryChanged (Signal) – signal emitted after graph category was changed
  • childGraphs (set) – a set of child graphs
  • nodes (dict) – nodes storage. Dictionary with uuid.UUID as key and NodeBase as value
  • uid (uuid.UUID) – Unique identifier
Tick(deltaTime)

Executed periodically

Parameters:deltaTime (float) – Elapsed time since last tick
__init__(name, manager, parentGraph=None, category='', uid=None, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

addNode(node, jsonTemplate=None)

Adds node to storage

Parameters:
  • node (NodeBase) – Node to add
  • jsonTemplate (dict) – serialized representation of node. This used when graph deserialized to do custom stuff after node will be added.
Return type:

bool

clear()

Clears content of this graph as well as child graphs. Deepest graphs will be cleared first

count()

Returns number of nodes

Return type:int
createVariable(dataType='AnyPin', accessLevel=<AccessLevel.public: 0>, uid=None, name='var')

Creates variable inside this graph scope

Parameters:
  • dataType (str) – Variable data type
  • accessLevel (AccessLevel) – Variable access level
  • uid (uuid.UUID) – Variable unique identifier
  • name (str) – Variable name
depth()

Returns depth level of this graph

Return type:int
findNode(name)

Tries to find node by name

Parameters:name (str or None) – Node name
findPin(pinName)

Tries to find pin by name

Parameters:pinName (str) – String to search by
Return type:PinBase or None
findPinByUid(uid)

Tries to find pin by uuid

Parameters:uid (UUID) – Unique identifier
Return type:PinBase or None
getInputNode()

Creates and adds to graph graphInputs node

pins on this node will be exposed on compound node as input pins :rtype: NodeBase

getNodes()

Returns this graph’s nodes storage

Return type:dict(NodeBase)
getNodesByClassName(className)

Returns a list of nodes filtered by class name :param className: Class name of target nodes :type className: str :rtype: list(NodeBase)

getNodesList(classNameFilters=[])

Returns this graph’s nodes list :rtype: list(NodeBase)

getOutputNode()

Creates and adds to graph graphOutputs node.

pins on this node will be exposed on compound node as output pins :rtype: NodeBase

getVarList()

return list of variables from active graph

Return type:list(Variable)
getVars()

Returns this graph’s variables storage

Returns:uuid.UUID - NodeBase dict
Return type:dict
isRoot()

Whether this graph is root or not

Return type:bool
killVariable(var)

Removes variable from this graph

Parameters:var (Variable) – Variable to remove
location()

Returns path to current location in graph tree

Example:

>>> ["root", "compound1", "compound2"]

means:

>>> # root
>>> # |- compound
>>> #    |- compound2
Return type:list(str)
plot()

Prints graph to console. May be useful for debugging

populateFromJson(jsonData)

Populates itself from serialized data

Parameters:jsonData (dict) – serialized graph
remove()

Removes this graph as well as child graphs. Deepest graphs will be removed first

serialize(*args, **kwargs)

Returns serialized representation of this graph

Return type:dict
setIsRoot(bIsRoot)

Sets this graph as root

Warning

Used internally

Parameters:bIsRoot (bool) – – Root or not

PyFlow.Core.GraphManager module

class PyFlow.Core.GraphManager.GraphManager

Bases: object

Data structure that holds graph tree

This class switches active graph. Can insert or remove graphs to tree, can search nodes and variables across all graphs. Also this class responsible for giving unique names.

Tick(deltaTime)

Periodically calls Tick() on all graphs

Parameters:deltaTime (float) – Elapsed time from last call
__init__()

Initialize self. See help(type(self)) for accurate signature.

activeGraph()

Returns active graph

Return type:GraphBase
add(graph)

Adds graph to storage and ensures that graph name is unique

Parameters:graph (GraphBase) – Graph to add
clear(keepRoot=True, *args, **kwargs)

Wipes everything.

Parameters:keepRoot (bool) – Whether to remove root graph or not
deserialize(data)

Populates itself from serialized data

Parameters:data (dict) – Serialized data
findGraph(name)

Tries to find graph by name

Parameters:name (str) – Name of target graph
Return type:GraphBase or None
findNode(name)

Finds a node across all graphs

Parameters:name (str) – Node name to search by
Return type:NodeBase
findPinByName(pinFullName)

Tries to find pin by name across all graphs

Parameters:pinFullName (str) – Full name of pin including node namespace
Return type:PinBase or None
findRootGraph()

Returns top level root graph

Return type:GraphBase
findVariableByName(name)

Finds a variable across all graphs

Parameters:name (str) – Variable name
Return type:Variable or None
findVariableByUid(uuid)

Finds a variable across all graphs

Parameters:uuid (UUID) – Variable unique identifier
Return type:Variable or None
findVariableRefs(variable)

Returns a list of variable accessors spawned across all graphs

Parameters:variable (Variable) – Variable to search accessors for
Return type:list(NodeBase)
getAllGraphs()

Returns all graphs

Return type:list(GraphBase)
getAllNames()

Returns list of all registered names

Includes graphs, nodes, pins, variables names

Return type:list(str)
getAllNodes(classNameFilters=[])

Returns all nodes across all graphs

Parameters:classNameFilters (list(str)) – If class name filters specified, only those node classes will be considered
Return type:list(NodeBase)
getAllVariables()

Returns a list of all variables

Return type:list(Variable)
getGraphsDict()

Creates and returns dictionary where graph name associated with graph

Return type:dict(str, GraphBase)
getUniqGraphName(name)

Returns unique graph name

Parameters:name (str) – Source name
Return type:str
getUniqGraphPinName(graph, name)

Returns unique pin name for graph

Used by compound node and graphInputs graphOutputs nodes. To make all exposed to compound pins names unique.

Parameters:
  • graph (GraphBase) – Target graph
  • name (str) – Target pin name
Return type:

str

getUniqName(name)

Returns unique name

Parameters:name (str) – Source name
Return type:str
getUniqNodeName(name)

Returns unique node name

Parameters:name (str) – Source name
Return type:str
getUniqVariableName(name)

Returns unique variable name

Parameters:name (str) – Source name
Return type:str
location()

Returns location of active graph

plot()

Prints all data to console. May be useful for debugging

removeGraph(graph)

Removes supplied graph

Parameters:graph (GraphBase) – Graph to be removed
removeGraphByName(name)

Removes graph by name

Parameters:name (str) – name of graph to be removed
selectGraph(graph)

Sets supplied graph as active and fires event

Parameters:graph (GraphBase) – Target graph
selectGraphByName(name)

Sets active graph by graph name and fires event

Parameters:name (str) – Name of target graph
selectRootGraph()

Selects root graph

serialize()

Serializes itself to json.

All child graphs will be serialized.

Return type:dict
terminationRequested = None

used by cli only

PyFlow.Core.Interfaces module

class PyFlow.Core.Interfaces.IEvaluationEngine

Bases: object

docstring for IEvaluationEngine.

__init__()

Initialize self. See help(type(self)) for accurate signature.

class PyFlow.Core.Interfaces.IItemBase

Bases: PyFlow.Core.Interfaces.ISerializable

Base class for pins and nodes

__init__()

Initialize self. See help(type(self)) for accurate signature.

getName()

Returns item’s name

Return type:str
Raises:NotImplementedError – If not implemented
getWrapper()

Returns reference to gui wrapper if it exists

Return type:gui class instance or None
kill()

Removes item

Raises:NotImplementedError – If not implemented
path()

Returns path to item

Raises:NotImplementedError – If not implemented
setName(name)

Sets item name

Parameters:name (str) – Target name
Raises:NotImplementedError – If not implemented
setWrapper(wrapper)

Sets gui wrapper

Parameters:wrapper (Whatever gui class) – gui class
class PyFlow.Core.Interfaces.INode

Bases: PyFlow.Core.Interfaces.IItemBase

__init__()

Initialize self. See help(type(self)) for accurate signature.

call(outPinName, *args, **kwargs)

call out exec pin by name

class PyFlow.Core.Interfaces.IPin

Bases: PyFlow.Core.Interfaces.IItemBase

Pin interface

static IsValuePin()

Defines is this pin is holding some data or not

For example, ExecPin is not a value pin

Return type:bool
Raises:NotImplementedError – If not implemented
__init__()

Initialize self. See help(type(self)) for accurate signature.

call(*args, **kwargs)

How to execute. What this should do is execute call on another pin, by using this we can evaluate nodes from left to right and define control flow

static color()

Defines pin color

Can be used by gui wrapper class.

Returns:Rgba tuple
Return type:typle(0, 0, 0, 255)
dataType

How to return this pin data type

Return type:str
Setter:How to set this pin data type
defaultValue()

Default value for this pin

Return type:object
Raises:NotImplementedError – If not implemented
getData()

How to return data for this pin

Raises:NotImplementedError – If not implemented
static internalDataStructure()

Static hint of what real python type is this pin

Return type:object
Raises:NotImplementedError – If not implemented
isAny()

Is this pin of type Any or not

Return type:bool
Raises:NotImplementedError – If not implemented
isArray()

Is this pin holds an list of values or not

Return type:bool
Raises:NotImplementedError – If not implemented
isExec()

Is this pin executable or not

Return type:bool
Raises:NotImplementedError – If not implemented
static processData(data)

Defines how data is processed

Returns:Processed data
Return type:object
Raises:NotImplementedError – If not implemented
setData(value)

How to set data to pin

Parameters:value (object) – Value to set
Raises:NotImplementedError – If not implemented
static supportedDataTypes()

List of supported data types

List of data types that can be casted to this type. For example - int can support float, or vector3 can support vector4 etc.

Return type:list(object)
Raises:NotImplementedError – If not implemented
class PyFlow.Core.Interfaces.ISerializable

Bases: object

Interface for serialization and deserialization

__init__()

Initialize self. See help(type(self)) for accurate signature.

deserialize(jsonData)

Implements how item will be deserialized

Raises:NotImplementedError – If not implemented
serialize(*args, **Kwargs)

Implements how item will be serialized

Raises:NotImplementedError – If not implemented

PyFlow.Core.NodeBase module

class PyFlow.Core.NodeBase.NodeBase(name, uid=None)

Bases: PyFlow.Core.Interfaces.INode

__init__(name, uid=None)

Initialize self. See help(type(self)) for accurate signature.

autoAffectPins()

All value inputs affects on all value outputs. All exec inputs affects on all exec outputs

call(name, *args, **kwargs)

Call exec pin by name

Parameters:name (str) – Target pin name
compute(*args, **kwargs)

This is node’s brains. Main logic goes here

Here are basic steps:

  1. Get data from input pins
  2. Do stuff
  3. Set data to output pins
  4. Call execs if needed

Here is compute method of charge node

1
2
3
4
5
6
7
def compute(self, *args, **kwargs):
    step = abs(self.step.getData())
    if (self._currentAmount + step) < abs(self.amount.getData()):
        self._currentAmount += step
        return
    self.completed.call(*args, **kwargs)
    self._currentAmount = 0.0

Note

See PyFlow.Packages.PyFlowBase.Nodes source code module for more examples

createInputPin(pinName, dataType, defaultValue=None, foo=None, structure=<StructureType.Single: 0>, constraint=None, structConstraint=None, supportedPinDataTypes=[], group='')

Creates input pin

Parameters:
  • pinName (str) – Pin name
  • dataType (str) – Pin data type
  • defaultValue (object) – Pin default value
  • foo (function) – Pin callback. used for exec pins
  • structure (Single) – Pin structure
  • constraint (object) – Pin constraint. Should be any hashable type. We use str
  • structConstraint (object) – Pin struct constraint. Also should be hashable type
  • supportedPinDataTypes (list(str)) – List of allowed pin data types to be connected. Used by AnyPin
  • group (str) – Pin group. Used only by ui wrapper
createOutputPin(pinName, dataType, defaultValue=None, structure=<StructureType.Single: 0>, constraint=None, structConstraint=None, supportedPinDataTypes=[], group='')

Creates output pin

Parameters:
  • pinName (str) – Pin name
  • dataType (str) – Pin data type
  • defaultValue (object) – Pin default value
  • structure (Single) – Pin structure
  • constraint (object) – Pin constraint. Should be any hashable type. We use str
  • structConstraint (object) – Pin struct constraint. Also should be hashable type
  • supportedPinDataTypes (list(str)) – List of allowed pin data types to be connected. Used by AnyPin
  • group (str) – Pin group. Used only by ui wrapper
getData(pinName, pinSelectionGroup=<PinSelectionGroup.BothSides: 2>)

Get data from pin by name

Parameters:
Return type:

object

getMetaData()

Returns node metadata dict.

This will return dict only for function based nodes. For class based nodes it will return None

See also

FunctionLibrary

Return type:dict or None
getName()

Returns item’s name

Return type:str
Raises:NotImplementedError – If not implemented
getPinByName(name)

Tries to find pin by name

Parameters:name (str) – pin name
Return type:PinBase or None
getPinSG(name, pinsSelectionGroup=<PinSelectionGroup.BothSides: 2>)

Tries to find pin by name and selection group

Parameters:
Return type:

PinBase or None

getUniqPinName(name)

Returns unique name for pin

Parameters:name (str) – Target pin name
Return type:str
getWrapper()

Returns reference to gui wrapper if it exists

Return type:gui class instance or None
static initializeFromFunction(foo)

Constructs node from annotated function

Parameters:foo (function) – Annotated function
Return type:NodeBase
inputs

Returns all input pins. Dictionary generated every time property called, so cache it when possible.

isCallable()

Whether this node is callable or not

kill(*args, **kwargs)

Removes item

Raises:NotImplementedError – If not implemented
namePinInputsMap

Returns all input pins. Dictionary generated every time property called, so cache it when possible.

namePinOutputsMap

Returns all output pins. Dictionary generated every time property called, so cache it when possible.

outputs

Returns all output pins. Dictionary generated every time property called, so cache it when possible.

path()

Returns path to item

Raises:NotImplementedError – If not implemented
postCreate(jsonTemplate=None)

Called after node was added to graph

Parameters:jsonTemplate (dict or None) – Serialized data of spawned node
serialize()

Implements how item will be serialized

Raises:NotImplementedError – If not implemented
setData(pinName, data, pinSelectionGroup=<PinSelectionGroup.BothSides: 2>)

Sets data to pin by pin name

Parameters:
  • pinName (str) – Target pin name
  • data (object) – Pin data to be set
  • pinSelectionGroup (PinSelectionGroup) – Which side to search
setName(name)

Sets item name

Parameters:name (str) – Target name
Raises:NotImplementedError – If not implemented
setPosition(x, y)

Sets node coordinate on canvas

Used to correctly restore gui wrapper class

Parameters:
  • x (float) – X coordinate
  • y (float) – Y coordinate
setWrapper(wrapper)

Sets gui wrapper

Parameters:wrapper (Whatever gui class) – gui class
class PyFlow.Core.NodeBase.NodePinsSuggestionsHelper

Bases: object

Describes node’s pins types and structs for inputs and outputs separately. Used by nodebox to suggest good nodes.

__init__()

Initialize self. See help(type(self)) for accurate signature.

PyFlow.Core.PathsRegistry module

PyFlow.Core.PinBase module

class PyFlow.Core.PinBase.PinBase(name, owningNode, direction)

Bases: PyFlow.Core.Interfaces.IPin

Base class for pins

This is the base class that stores the data in the graph. This class is intended to be subclassed for each new registered data type you want to create.

Parameters:_packageName (str) – This holds the package where the sub classed pin is registered. It is not intended to be set by developer, PyFlow automatically fills this property at registration point
Signals:
  • serializationHook : Fired when Serialize Pin called, so Ui wrapers can append data to the serialization
  • onPinConnected : Fired when a new connection is made to this Pin, sends other Pin
  • onPinDisconnected : Fired when some disconnection is made to this Pin, sends other Pin
  • nameChanged : Fired when pin.setName() called, sends New Name
  • killed : Fired when Pin gets deleted
  • onExecute : Fired when Pin execution gets called
  • containerTypeChanged : Fired when Pin Structure Changes
  • dataBeenSet : Fired when data changes, sends New Data
  • dictChanged : Fired when current structure changes to PyFlow.Core.Common.StructureType.Dict, sends Dict key DataType
  • errorOccurred : Fired when some error fired, like incorrect dataType set, sends ocurred Error
  • errorCleared : Fired when error cleared
Variables:
  • owningNode – Weak reference to owning node
  • reconnectionPolicy – What to do if connect with busy pin. Used when AllowMultipleConnections flag is disabled
  • dirty – This flag for lazy evaluation
  • affects – List of pins this pin affects to
  • affected_by – List of pins that affects to this pin
  • name – Pin name
  • direction – Pin direction
  • inputWidgetVariant – Input widget variant tag
  • constraintdescription here
  • structConstraintdescription here
  • superdescription here
  • activeDataType – Current data type of this pin. Used by AnyPin
  • pinIndex – Position of this pin on node
  • description – Text description of this pin
static IsValuePin()

Returns whether this pin is value pin or not

Return type:bool
__init__(name, owningNode, direction)

Initialize self. See help(type(self)) for accurate signature.

aboutToConnect(other)

This method called right before two pins connected

Parameters:other (PinBase) – Pin which this pin is going to be connected with
call(*args, **kwargs)

How to execute. What this should do is execute call on another pin, by using this we can evaluate nodes from left to right and define control flow

canChangeStructure(newStruct, checked=[], selfCheck=True, init=False)

Recursive function to determine if pin can change its structure

Parameters:
  • newStruct (string) – New structure we want to apply
  • checked (list, optional) – Already visited pins, defaults to []
  • selfCheck (bool, optional) – Define if check pin itself for connected pins, defaults to True
  • init (bool, optional) – Initialization flag, if set multi pins can became other structure and don’t be able to change after new call with init=True, defaults to False
Returns:

True if pin can change structure to newStruct

Return type:

bool

canChangeTypeOnConnection(checked=[], can=True, extraPins=[], selfCheck=True)

Recursive function to determine if pin can change its dataType

Parameters:
  • checked (list, optional) – Already visited pins, defaults to []
  • can (bool, optional) – Variable Updated during iteration, defaults to True
  • extraPins (list, optional) – extra pins, non constrained or connected to this pin but that want to check also, defaults to []
  • selfCheck (bool, optional) – Define if check pin itself for connected pins, defaults to True
Returns:

True if pin can becabe other dataType

Return type:

bool

changeStructure(newStruct, init=False)

Changes this pin structure type

Parameters:
clearError()

Clears any last error on this pin and fires event

currentData()

Returns current value of this pin, without any graph evaluation

Return type:object
dataType

Returns data type of this pin

Return type:str
defaultValue()

Returns default value of this pin

deserialize(jsonData)

Restores itself from supplied serialized data

Parameters:jsonData (dict) – Json representation of pin
disableOptions(*options)

Same as enableOptions() but inverse

enableOptions(*options)

Enables flags on pin instance

Example:

>>> self.pinInstance.enableOptions(PinOptions.RenamingEnabled)

You can also pass array/set of flags

>>> self.pinInstance.enableOptions({PinOptions.RenamingEnabled, PinOptions.Dynamic})

This is equivalent of

>>> self.pinInstance.enableOptions(PinOptions.RenamingEnabled | PinOptions.Dynamic)
getCurrentStructure()

Returns this pin structure type

Return type:StructureType
getData()

Returns pin value

If something is connected to this pin, graph will be evaluated

getDictElementNode(checked=[], node=None)

Get the connected PyFlow.Packages.PyFlowBase.Nodes.makeDictElement.makeDictElement to this pin recursively

Parameters:
  • checked (list, optional) – Currently visited pins, defaults to []
  • node – founded node, defaults to None
Return type:

NodeBase or None

getDictNode(checked=[], node=None)

Get the connected PyFlow.Packages.PyFlowBase.Nodes.makeDict.makeDict or PyFlow.Packages.PyFlowBase.Nodes.makeAnyDict.makeAnyDict to this pin recursively

Parameters:
  • checked (list, optional) – Currently visited pins, defaults to []
  • node – founded node, defaults to None
Returns:

founded node or None if not found

getFullName()

Returns full pin name, including node name

Return type:str
getName()

Returns item’s name

Return type:str
Raises:NotImplementedError – If not implemented
getWrapper()

Returns ui wrapper instance

group

Pin group

This is just a tag which can be used in ui level

Return type:str
hasConnections()

Return the number of connections this pin has

Return type:int
initAsArray(bIsArray)

Sets this pins to be a list always

Parameters:bIsArray (bool) – Define as array
initAsDict(bIsDict)

Sets this pins to be a dict always

Parameters:bIsArray (bool) – Define as dict
isAny()

Wheter this pin of type Any or not

Return type:bool
isArray()

Returns whether this pin is array or not

Return type:bool
isDict()

Returns whether this pin is dict or not

Return type:bool
isExec()

Returns whether this is exec pin or not

Return type:bool
static jsonDecoderClass()

Returns json decoder class for this pin

static jsonEncoderClass()

Returns json encoder class for this pin

kill(*args, **kwargs)

Deletes this pin

linkedTo

store connection from pins

from left hand side to right hand side

{
    "lhsNodeName": "", "outPinId": 0,
    "rhsNodeName": "", "inPinId": 0
}

where pin id is order in which pin was added to node

Returns:Serialized connections
Return type:list(dict)
optionEnabled(option)

Is option enabled or not

Parameters:option (PinOptions) – Option to check
Return type:bool
packageName

Returns name of package this pin belongs to

Return type:bool
path()

Returns path to item

Raises:NotImplementedError – If not implemented
static pinDataTypeHint()

Hint of what data type is this pin, as well as default value for this data type.

Used to easily find pin classes by type id.

Return type:tuple(str, object)
Raises:NotImplementedError – If not implemented
serialize()

Serializes itself to json

Return type:dict
setAsArray(bIsArray)

Sets this pins to be a list

Parameters:bIsArray (bool) – Define as Array
setAsDict(bIsDict)

Sets this pins to be a dict

Parameters:bIsArray (bool) – Define as Array
setClean()

Sets dirty flag to True

setData(data)

Sets value to pin

Parameters:data (object) – Data to be set
setDefaultValue(val)

In python, all user-defined classes are mutable So make sure to store separate copy of value For example if this is a Matrix, default value will be changed each time data has been set in original Matrix

Parameters:val (object) – defaultValue
setDirty()

Sets dirty flag to True

setError(err)

Marks this pin as invalid by setting error message to it. Also fires event

Parameters:err (str) – Error message
setName(name, force=False)

Sets pin name and fires events

Parameters:
  • name (str) – New pin name
  • force (bool) – If True - name will be changed even if option RenamingEnabled is turned off
Returns:

Whether renaming performed or not

Return type:

bool

setWrapper(wrapper)

Sets ui wrapper instance

Parameters:wrapper – Whatever ui class that represents this pin
structureType

Returns current structure of this pin

Return type:StructureType
supportDictElement(checked=[], can=True, selfCheck=True)

Iterative functions that search in all connected pins to see if they support DictElement nodes.

Parameters:
  • checked (list, optional) – Already visited pins, defaults to []
  • can (bool, optional) – this is the variable that will be actualized during the recursive function, defaults to False
  • selfCheck (bool, optional) – Define if look itself or no, defaults to True
Returns:

True if can connect DictElement nodes to this pin

Return type:

bool

supportOnlyDictElement(checked=[], can=False, selfCheck=True)

Iterative Functions that search in all connected pins to see if they support only DictElement nodes, this is done for nodes like makeDict and simmilars.

Parameters:
  • checked (list, optional) – Already Visited Pins, defaults to []
  • can (bool, optional) – this is the variable that will be actualized during the recursive function, defaults to False
  • selfCheck (bool, optional) – Defines if look itself or no, defaults to True
Returns:

True if can connect only DictElement and Dicts nodes to this Pin

Return type:

bool

static supportedDataTypes()

List of supported data types

List of data types that can be casted to this type. For example - int can support float, or vector3 can support vector4 etc.

Return type:list(object)
Raises:NotImplementedError – If not implemented
updateConnectedDicts(checked=[], keyType=None)

Iterate over connected dicts pins and DictElements pins updating key data type

Parameters:
  • checked (list, optional) – Already visited pins, defaults to []
  • keyType (string, optional) – KeyDataType to set, defaults to None

PyFlow.Core.PyCodeCompiler module

class PyFlow.Core.PyCodeCompiler.Py3CodeCompiler

Bases: PyFlow.Core.Interfaces.ICodeCompiler

Generic python code compiler

__init__()

Initialize self. See help(type(self)) for accurate signature.

compile(code, moduleName='PyFlowCodeCompiler', scope={})

Evaluates supplied string

Used by python node

Parameters:
  • code (str) – Whatever python code
  • moduleName (str) – Used for runtime error messages
  • scope (dict) – Storage where symbols will be placed
class PyFlow.Core.PyCodeCompiler.Py3FunctionCompiler(fooName=None, *args, **kwargs)

Bases: PyFlow.Core.Interfaces.ICodeCompiler

Compiles string to python function

__init__(fooName=None, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

compile(code)

Wraps code to function def

Parameters:code (str) – Code to wrap
Returns:Function object
Return type:function

PyFlow.Core.Variable module

class PyFlow.Core.Variable.Variable(graph, value, name, dataType, accessLevel=<AccessLevel.public: 0>, structure=<StructureType.Single: 0>, uid=None)

Bases: PyFlow.Core.Interfaces.IItemBase

Variable representation

Variables:
  • nameChanged (Signal) – Fired when variable name was changed
  • valueChanged (Signal) – Fired when variable value was changed
  • dataTypeChanged (Signal) – Fired when variable data type was changed
  • structureChanged (Signal) – Fired when variable structure was changed
  • accessLevelChanged (Signal) – Fired when variable access level was changed
  • killed (Signal) – Fired when variable was killed
  • graph (GraphBase) – Reference to owning graph
__init__(graph, value, name, dataType, accessLevel=<AccessLevel.public: 0>, structure=<StructureType.Single: 0>, uid=None)

Constructor

Parameters:
  • graph (GraphBase) – Owning graph
  • value (object) – Variable value
  • name (str) – Variable name
  • dataType (str) – Variable data type
  • accessLevel (AccessLevel) – Variable access level
  • structure (Single) – Variable structure
  • uid (UUID) – Variable unique identifier
accessLevel

Variable access level

Return type:AccessLevel
dataType

Variable data type

Return type:str
static deserialize(graph, jsonData, *args, **kwargs)

Implements how item will be deserialized

Raises:NotImplementedError – If not implemented
findRefs()

Returns all getVar and setVar instances for variable

getWrapper()

Returns reference to gui wrapper if it exists

Return type:gui class instance or None
static jsonTemplate()

Returns dictionary with minimum required fields for serialization

Return type:dict
location()

Returns location of variable

See also

location()

packageName

Variable type package name

Return type:str
serialize()

Implements how item will be serialized

Raises:NotImplementedError – If not implemented
setWrapper(wrapper)

Sets gui wrapper

Parameters:wrapper (Whatever gui class) – gui class
structure

Variable structure

Return type:StructureType
value

Variable value

Return type:object

PyFlow.Core.structs module

class PyFlow.Core.structs.Tick

Bases: object

Element For Ramp Widget Basic U and V Attribute holder

__init__()

Initialize self. See help(type(self)) for accurate signature.

class PyFlow.Core.structs.splineRamp

Bases: object

Ramp/Curve Editor with evaluateAt support , clamped to 0-1 in both x and y

__init__()

Initialize self. See help(type(self)) for accurate signature.

PyFlow.Core.version module

class PyFlow.Core.version.Version(major, minor, patch)

Bases: object

Version class according to semantic versioning

Comparison operators overloaded

__init__(major, minor, patch)

Initialize self. See help(type(self)) for accurate signature.

static fromString(string)

Constructs version class from string

>>> v = Version.fromString("1.0.2")
Parameters:string (str) – Version as string
PyFlow.Core.version.currentVersion()

Returns current version of program

Module contents

Core functionality of the PyFlow.

This module will be eventually moved to own repo.