0

I'm trying to figure out some problem I have. I have written small program just for the example here (which i'll implement the solution in the real one :) )

So, I have 3 files One -Which is the main Test -Which is the test I run CounterTest -Which has class with def inside

One:

def main():
    CounterTest=1
    execfile("c:\\111\\Test.py") 
if __name__ == '__main__':

    main()

Test:

from CounterTest import *
print "THIS IS THE TEST"
CallClass=CounterTest1()
CallClass.CounterPlus()

CounterTest:

class CounterTest1():
   def CounterPlus(self):
        CounterTest +=1
        print CounterTest

Scenario: I run "one" which execute file Test (All this happen in main def) In "Test" I'm calling class and def -in def we counter +1 , that was defined in "one" file.

I'm getting "local variable 'CounterTest' referenced before assignment"

I have tried everything but nothing worked

Appriciated ,

Thanks

ohadshay
  • 225
  • 1
  • 3
  • 16

1 Answers1

0

The long and short of it is that you can't. If I'm understanding your process correctly you are:

1. Running main.py.
2. Defining the variable INSIDE a function so it's non-global

def main():
    CounterTest = 1  # <-- right here

3. Executing code from a different file

    execfile("...")

4. Which imports a THIRD file

from CounterTest import *

5. That attempts to modify a global in the first file

...
    CounterTest += 1

You can't do that. You're three levels of "nope" away from that.

  1. main.py's CounterTest isn't a global, so it's only available inside def main's scope.
  2. Even if it were global, test.py doesn't have access to main.py's globals without passing them explicitly.
  3. Even if you passed them explicitly (using execfile(path, globals_dict, locals_dict)), and they became globals inside test.py, CounterTest.py isn't allowed to see test.py's globals.

You can't even monkey around with things to make that okay. You need to paramaterize values and you need to stop using globals. This whole thing SHOULD be:

# counter.py
class Counter(object):
    """Counter is knows how to add to itself"""
    def __init__(self, value=1):
        self.__value = value
    def increment(self):
        self.__value += 1
    @property
    def value(self):
        return self.__value


# main.py

import counter

c = counter.Counter()  # initializes at 1

print(c.value)  # 1
c.increment()
print(c.value)  # 2

# now SHARE that instance of c!!
Adam Smith
  • 52,157
  • 12
  • 73
  • 112