0

I have two files.

first.py

Class Repo:
   def my_function:
     variable = []

Now, I've second file in different directory and want to create something like:

second.py

def my_second_function(variable):
  print(variable) # or some other operations on variable

What can I do to make my above code works? I tried something like:

import sys
sys.path.insert(1, 'path')
from first import *

but it doesn't work. Do you have any ideas?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Did you do a web search on this question? This could help: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder – David Wierichs Jun 09 '20 at 13:52
  • Yes, I saw that but it doesn't help. –  Jun 09 '20 at 13:55
  • How does the sys.path.insert not work? Do you get an error? And sorry, I overlooked the fact that `variable` is defined in `my_function`. It will therefore be accessible within the function unless you make it a `global` variable. – David Wierichs Jun 09 '20 at 13:56
  • But how to covert this variable to global? I think, that "global variable" is not enough. –  Jun 09 '20 at 14:00
  • Could you provide some context how you want to use the variable? As you seem to have some class defined, you could make the variable an attribute of the class or its instances? – David Wierichs Jun 09 '20 at 14:02
  • I faced this error: NameError: global name 'variable' is not defined. Regarding your above question, this variable is a list and in my_second_function I want to use it to other operations like append etc. –  Jun 09 '20 at 14:08

1 Answers1

1

Although it is not entirely clear to me what you are aiming at, here is a way to define a global variable within one file, which then can be imported via the sys.path approach you tried:

test_dir/file1.py:

global_var1 = 'global_var1' # This variable is available upon import of file1.py
def fun():
    global global_var2
    global_var2 = 'global_var2' # This variable will be available after having called fun()

file2.py:
import sys
sys.path.insert(1, 'test_dir')
import file1

print(file1.global_var1)
#print(file1.global_var2) # This would fail
file1.fun()
print(file1.global_var2) # This works
David Wierichs
  • 545
  • 4
  • 11