0

I'm having serious trouble sorting out scoping error in my project. My project looks something like this:

There is this mainfile wich contains the process and creates the gui with tkinter

interfaceAndProcess.pyw
import lib1
...
#do something with tkinter
filePath = askopenfilename(filetypes=(("All files", "*.*")))
...
lib1.checkSomeDocument(filePath)

Then I have a "motherOfAllLlibs" where other libs get the functions from.

moalibs.py

def parseSomething(lookForStringX)
  position = line.index(lookForStringX, 0)
  return(position)

def bla():
  ...

def blabla():
  ...

And here is one of many libs which use the methods from moalibs.py

lib1.py
from moalibs import *
def checkSomeDocument(filePath)
global line
  fileContent = open(filePath, 'r')
  for line in fileContent:
    tmpVar = parseSomething(lookForStringX)
    ...
    tmpVar = bla()
    ...
    tmpVar = blabla()
    ...
    tmpVar = bla()
    # In any of my many libs the methods from moalib are called
    # serveral times in different orders, that's why this part
    # is pretty "hard coded"

My problem is, that the execution of interfaceAndProcess.pyw throws an NameError on the line where lib1 calls the function parseSomething(lookForStringX) saying "name 'line' is not defined".

Why can't parseSomething see the var line?

When I put parseSomething in the file moalibs.py everthing is working fine.

I'm sorry for this question to be pretty specific but I'm searching and trying for for more than two hours now. Been playing with global line inside the methods, been defining line inside interfaceAndProcess.pyw, nothing...

Any suggestions?

Edit: Ok, I understood that what I have tried can't work as I expected. How would I achieve this without passing the variable as an argument?

an d re
  • 153
  • 2
  • 6
  • `global` isn't actually global. It's module-level. Functions from one module won't look in another module's globals for name resolution. – user2357112 Apr 19 '17 at 22:47

1 Answers1

0

For starters, the global keyword isn't doing anything for a variable already in the top-level namespace (as is line in this case). This Stack Overflow question discusses why.

The reason you're getting a NameError is because lib1.py imports the namespace of moalibs.py, not vice-versa. You made line global, in lib1.py, but moalibs.py doesn't import lib1.py.

To see what I mean, you can ask each module to tell you its current namespace contents by using the dir() function. You'll find that lib1.py is fully aware of all of moalibs.py's identifiers, but moalibs.py is not aware of lib1.py's identifiers.

Community
  • 1
  • 1
Matthew Cole
  • 602
  • 5
  • 21
  • Thank you for your answer. But I also tried importing lib1.py in moalib.py. Wihtout any success – an d re Apr 20 '17 at 04:49