How to share global variables between python files

I have one task list (tasks = [task1,task2,task3]) to be executed using AGV caller, however new task will be assigned using tasks.append(new task) as well when running the current task list. How can two scripts using the same global variable. I tested the import X.py module like below doesn’t work.

===============================================

File: config.py

x =0 # Default value of the ‘x’ configuration setting
File: mod.py

import config
config.x = 1
File: main.py

import config
import mod
print config.x

==============================================

My only advice would be use a component property or add a property to an object like a behavior that can be accessed by getting the object.

This is a feature that is really missing and it is on my personal feature wish list since several years. At the moment it is only possible to share values of component properties or to send signals between the scripts as zesty already mentioned.

The only way that succeed for me without using that sharing is to use the ctypes module and working with ctypes pointers from integer addresses. But for a clear working you need a lot of overhead to organize the python objects.

I agree something like that would be awesome!

Check this…Python Global Variables across modules

I started ~ two weeks ago with VisualComponents.
Maybe it helps, if you use a class to automatic add Properties
to a Component. This is what I have done:

from __future__ import print_function
from collections import OrderedDict

import sys

from vcScript import *


class GlobalVariables(object):
  _variables = OrderedDict()

#  def __init__(self, properties=None):
#      if properties is not None:
#        for name, property in properties.items():
#          self[name] = property

  def __getitem__(self, key):
    return self._variables.get(key)

  def __setitem__(self, key, variable):
    if key in self._variables:
      return
    self._variables[key] = variable

  def __len__(self):
    return len(self._variables)

  def __repr__(self):
    return 'GlobalVariables({})'.format(
      list(self._variables.keys())
    )
  
  def __iter__(self):
    for item in self._variables.items():
      yield item

  __getattr__ = __getitem__


class GlobalVariable(object):
  _register = GlobalVariables()
  _type_mapping = {
    str: VC_STRING,
    int: VC_INTEGER,
    float: VC_REAL,
    bool: VC_BOOLEAN,
  }
  _inv_type_mapping = {v: k for k, v in _type_mapping.items()}

  def __init__(self, name, type, component_name="GlobalVariables"):
    self._app = getApplication()
    self._prop_name = name
    self._component_name = component_name
    self._type = type
    self._prop = self._find_prop()
    self._validate(self._prop)
    self._register[name] = self
  
  def _validate(self, prop):
    expected_prop_type = prop.Type
    expected_python_type = self._inv_type_mapping[prop.Type]
    given_python_type = self._type
    if expected_python_type != given_python_type:
      raise ValueError(
        'The property is a type of {} and '
        'the expected Python type is {}, '
        'but got type {} instead.'.format(
          expected_prop_type,
          expected_python_type,
          given_python_type,
        )
      )

  def _get_component(self):
    comp = self._app.findComponent(self._component_name)
    if not comp:
      comp = self._app.createComponent()
      comp.Name = self._component_name
    return comp

  def _get_property(self, comp):
    prop = comp.getProperty(self._prop_name)
    if not prop:
      prop = comp.createProperty(self._type_mapping[self._type], self._prop_name)
    return prop

  def _find_prop(self):
    comp = self._get_component()
    prop = self._get_property(comp)
    return prop

  def get(self):
    return self._prop.Value

  def set(self, value):
    if not isinstance(value, self._type):
      raise ValueError('Got wrong data type {}. Excpected type {}'.format(self._type, type(value)))
    self._prop.Value = value
  
  @property
  def value(self):
    return self.get()
  
  @value.setter
  def value(self, value):
    self.set(value)

  def __call__(self, value=None):
    if value is None:
      return self.get()
    self.set(value)
    return value

  def __repr__(self):
    return 'GlobalVariable(name="{}", type="{}", component_name="{}")'.format(
      self._prop_name,
      self._type,
      self._component_name,
    )
  
  def __eq__(self, other):
    cond1 = self._prop_name == other._prop_name
    cond2 = self._component_name == other._component_name
    return cond1 and cond2
  
  def __bool__(self):
    return bool(self.get())
  
  __nonzero__ = __bool__

print('Getting or creating Properties and Component')
all_vars = GlobalVariables()
foo = GlobalVariable('foo', int)
bar = GlobalVariable('bar', bool)
baz = GlobalVariable('fizz', float)
faz = GlobalVariable('faz', str)
print('Trying an exception...')
try:
  GlobalVariable('bar', float)
  # bar exists already with the type bool
  # this does not match
except ValueError as e:
  print('Catching Error:', e, file=sys.stderr)

print()
print('Creating another bar instance')
# creating another instance for 'bar'
bar2 = GlobalVariable('bar', bool) # this time the right type

print('Get bool of bar', bool(bar), bool(bar2), sep=',')
print('Value of bar and bar2:', bar.value, bar2.value, sep=', ')
print('Modify bar2 -> True')
bar2.value = True
# bar2(True)
# bar2.set(True)
print('Get bool of bar', bool(bar), bool(bar2), sep=', ')

print('Testing equallity')
print(bar == bar2)

#print()
#print('Representation:', all_vars)
#print('Converted to a list', list(all_vars))


print(all_vars.bar)
print(all_vars.bar.value)
all_vars.bar.value = False
print(all_vars.bar.get())

By the way, it sucks, that there is still Python 2.7 syntax used.
I want format strings, I want typehints, I want asyncio, I want modern Python!

In Python, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.

Create a Global module

#global.py
current_value=0

Create a Python program file to access global variable

#updater.py
import global
def update_value():
global.current_value = 100

Create another Python program to test value is changed or not

#display_value.py
import global
import updater
updater.update_value()
print(global.current_value)

 

Hello galewinston,

if I import a own python script I get the same result like captain_feature here: https://forum.visualcomponents.com/t/how-to-import-pyodbc/243

So do u have a solution for this issue?
Thanks