how to create a global variable in python function

Hello
Can someone tell me how to create a global variable in a Python function

node-red-contrib-python-function
Node Red V3.1.3

Hello @Kleisi, welcome to the forum.

Can you explain why you want to do that?
Would it work to set the variable in a change node using the output of your python node?

Hello

I want to count signals or use calculations in other Python functions in other flows

and because I'm just interested :slight_smile:

I could be wrong,

But what you are trying to achieve is not possible.

Each python function node creates a new python process.

You don’t have the likes of global variables with this approach.

Like @jbudd says - use the Node RED globals to pass values to and from the python scripts.

But remember - the scripts are not in the same process as they are in Node RED

1 Like

Or replace the python functions with node red flows.

2 Likes

There is a valuable and little known feature in Node-red for passing data between different flow tabs and internal & external processes: messages.

You can think of a message like a railway train. It travels along a prescribed track. At every stop different people and luggage can join the train and they are carried safely onward to their destination.

A context variable is a viable way to do this. But global context is ridiculous overkill. Use a variable whose scope is restricted to a flow or even a single node and put that value on the train for use further down the track.

A little javascript function to achieve this:

let signalCount = context.get("signalCount") || 0
signalCount += 1
context.set("signalCount", signalCount)
msg.signalCount = signalCount
return msg

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.