Scott Scott - 1 year ago 94
Python Question

How to modify variables in another python file?

windows 10 - python 3.5.2

Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.

from X.secondfile import *

def edit():
#editing second file's variables by user input
if Language == 'en-US':
print('language is English-us')
elif Language == 'en-UK':
print('language is English-uk')

Language = 'en-US'

i can add some variables to it by following code, but how can i edit one ?

with open("","a") as f:
f.write("Language = 'en-US'")

Any ideas how to do that?

Answer Source

You can embed the Language in a class in the second file that has a method to change it.

Module 2

class Language:
    def __init__(self):
        self.language = 'en-US'

    def __str__(self):
        return self.language

    def change(self, lang):
        assert isinstance(lang, str)
        self.language = lang

language = Language()

Then import the "language," and change it with the change method.

Module 1

from module2 import language

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download