7

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.

firstfile.py

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')

secondfile.py

Language = 'en-US'

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

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

Any ideas how to do that?

2 Answers 2

7

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

print(language)
language.change("test")
print(language)
3
  • @pycoder We wrote the same thing. Great minds think alike ;)
    – zvone
    Sep 10, 2016 at 12:13
  • does it update module 2 after language.change("test") ? i want it to save it for next time Sep 10, 2016 at 12:39
  • 2
    Yes, it does, but of course it doesn't actually change the file (you can't exit the program and reopen it b/c it doesn't write to a file). But if you add in a third module that prints out language after you changed it in module 1, it will say "test." I assume that's what you want. If you want it to save between "sessions," you will need to write it out to some sort of file (pickling, plain text, etc.).
    – JakeD
    Sep 10, 2016 at 14:54
2

This can be done to edit a variable in another file:

import X.secondfile
X.secondfile.Language = 'en-UK'

However, I have two suggestions:

  1. Don't use import * - it pollutes the namespace with unexpected names

  2. Don't use such global variables, if they are not constants. Some code will read the value before it is changed and some afterwards. And none will expect it to change.

So, rather than this, create a class in the other file.

class LanguagePreferences(object):
    def __init__(self, langcode):
        self.langcode = langcode

language_preferences = LanguagePreferences('en-UK')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.