-1

Lets say FileA and FileB are my two files that do stuff. FileA has as an import FileB has some variables and functions. The Function I want to call in FileA from FileB is X which is using some other variables and functions of FileB. When I try to run the program I get an error saying that "Cannot acces local variable if it's not defined". Now I imagine that it would get all the stuff I declared in FileB but it doesn't. How can I go about this without making my program have a ton of references? Can't I just run my function from FileA while using FileB contents? Note that I am a beginner and it might be a stupid question! And also I will compile the files togheter at the end if it's of any help.

EDIT: If I declare Pas inside my function it does work! But I have too many things to define inside it. Why won't it pick up the context from FileB ?

Example in Code: FileA

import FileB as fb

print(fb.X())

FileB

import random
global Pas
p = "ok"
u = [some randomly generated stuff]

def RandomLetterGen:
   some code

Pas = ""
def X():
 Pas += RandomLetterGen()
 return Pas

This is an easy to understand example but my code does much more to get to the result of the X function in FileB

I tried looking it up online but no luck.

Teroro
  • 3
  • 5
  • Post the exact traceback instead of describing it. And post real (minimal) code that you've tested - the code you've shown has syntax errors and other issues. – interjay Jun 20 '23 at 12:16

3 Answers3

0

The following FileB works OK for me

import random
p = "ok"
u = "[1, 2, 3]"

def X():
 return p + u

Maybe it's something to do with your u variable rather than the 2 files. Adding a list to a string will also cause a problem.

quite68
  • 31
  • 7
0

You have an Error at a different place since the acces to local variables works in Python. This example will work:

File A:

import FileB as fb
print(fb.getP())

File B:

p = "ok"

def getP():
 return p

My guess is that your Error is in calculating value

u = [some randomly generated stuff]

I guess here you try to access a local variable in a different function. Have a look here for solutions: "cannot access local variable 'a' where it is not associated with a value", but the value is defined

0

Do you need to initialize Pas inside the X() function?

def X():
 Pas = ""
 Pas += RandomLetterGen()
 return Pas
Austin
  • 39
  • 3
  • It does work but I have already defined all of my variables global – Teroro Jun 20 '23 at 12:29
  • To answer your edit @Teroro, this works because the declaration of Pas is now in scope of the function. – Austin Jun 20 '23 at 12:33
  • If I imported all the fileB can't I make it to automaticly search in **FileB** for these ? – Teroro Jun 20 '23 at 12:35
  • you need to use the **global** keyword if you want to reassign the global variable within a function. If you just need to read or access the value of the global variable from within your function, then you don’t need the **global** keyword – Austin Jun 20 '23 at 12:45