-1

I need to get arguments from a function imported into another python file however when ever I try to do this:

file1.py

def func(x):
  x += 1

func(10)

import file2

file2.py

from file1 import *
print(x)

Output:

NameError: name 'x' is not defined

Expected output: 11

I researched this a bit and saw that it might be caused by a circular import so I tried to get around this by running file2 from a file other than file1:

file1.py

def func(x):
  x += 1
func(10)

import file_that_runs_file2

#file_that_runs_file2.py
import file2

file 2

from file1 import *
print(x)

Output:

NameError: name 'x' is not defined

Expected output: 11

Still the same error. I thought this would work because technically I'm not importing file1 from file2 and file2 from file1.

(Also, please provide an answer that would work for dictionaries, I just used a variable as an example.)

James Z
  • 12,104
  • 10
  • 27
  • 43
  • 3
    this error is not caused by circular imports, ```x``` is only defined within the function ```func``` – Nin17 May 31 '22 at 13:42
  • 1
    `x` is a local variable. It is not even visible elsewhere in the file, much less another file. if you want it to be global, then you need to declare it `global`. The other file would then need to import that file into its own namespace so you can modify it and have it be visible in the first file (if that's the intent). – Tom Karzes May 31 '22 at 13:43
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Pranav Hosangadi May 31 '22 at 14:08

0 Answers0