Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable not changing between files in python

I have kept the global variables in a file and importing this file into two files. One in which the value of this global variable is being changed and another in which this changed value is to be used.

In 1st file , inside a class

from globals.py import *
.
.
.class ...
    def uploadClick(self):
        global filename
        filename = dialog.askopenfilename()
        print(filename)

In 2nd file

from globals.py import *
.
.
.
  def mainAnalysis():
    global filename , semantic_orientation
    print("filename = "+filename)
    n_docs=0
    with open(filename, 'r') as f:
        count_all = Counter()

In globals file

filename =''

The mainAnalysis function is called after the uploadClickfunction.

I get an error saying the filename is empty when mainAnalysis function runs

like image 424
Kitwradr Avatar asked Oct 15 '25 21:10

Kitwradr


1 Answers

The syntax from globals.py import * makes copies of the variables within globals.py into your local file. To access the variables themselves without making copies, import globals and use the variable directly: globals.filename. You no longer need the global keyword if you access the variable this way.

like image 175
TheoretiCAL Avatar answered Oct 18 '25 10:10

TheoretiCAL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!