"extern variable" in PYTHON:

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • balachandra

    "extern variable" in PYTHON:

    I have a file fileA.py where my students input some data and fill in a certain portion of the code. There are a few functions they call from a module, fileB.py inside the file fileA.py. When they are calling functions, I do not want them to pass data as arguments , since that would confuse them a lot (they are 9th grade students). So, I want to make the data of fileA.py available to fileB.py. I cannot use

    from __fileA__ import *

    because, that will be a recursive call. I have already used it in fileA.py. So, I need a way out of this, where I can use variable defined in fileA.py to be used by fileB.py. I had an idea of creating a bypass.py such that

    fileA calls functions from fileB.

    Functions in fileB call functions from bypass.py

    bypass.py accesses fileA.py and returns to fileB.py.

    So, the recursion is kind of avoided.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You could do something like this:
    Code:
    # FileA.py
    
    import FileB
    
    a = 12
    b = 24
    c = 24
    
    for attr in ('a', 'b', 'c'):
        setattr(FileB, attr, eval(attr))
    
    result = FileB.f()

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      They should be able to understand writing the data to a file and closing the file. The function in fileB would open and read the file. Also, you can use a class attribute, but that is possibly beyond them as well.
      Code:
      ## file classC.py
      class Class_C:
         test_string = "abc"
         test_number = 1
      
      ## fileA
      import classC
      import fileB
      
      print classC.Class_C.test_string
      classC.Class_C.test_number = 2
      fileB.print_number()
      
      ## fileB
      import classC
      
      def print_number():
          print "inside fileB", classC.Class_C.test_number

      Comment

      Working...