Ignus
Ignus

Reputation: 139

Mutual dependancies between python file

I am writing a program and I want to keep the CORE of my program separate from the GUI (built with Tkinter). However, having two separate python files I'm experiencing the following problem:

GUI.py

def bar():
    if a == 'something':
        foo()   

Button(text="START!", command=bar).grid(row=1, column=1)

CORE.py

from GUI import *

 def foo():
    <do something>

and when I launch my program from CORE.py I get:

NameError: name 'foo' is not defined

I do not know exactly where or what to look for.

Upvotes: 0

Views: 54

Answers (3)

Isma
Isma

Reputation: 15190

I think you should reference your modules the other way around:

# core.py
def foo():
    # Do something

And then from the GUI module you reference and call your core module

# gui.py
from core import foo

def bar():
    foo()

Upvotes: 2

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Having distinct layers for the domain (what you call "core") and the UI is a very sane design, but only if the domain knows nothing of the UI - it's the UI that must depend on the domain, not the other way round. IOW, you don't want to import "gui" in "core" but to import "core" in "gui".

If the gui needs to be notified of some events / conditions by the core, you can use some variant of the observer pattern.

As a side note: never use star imports ("from something import *") - except possibly in a python shell or a one-shot throw-away script - if you value your mental sanity.

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191743

You have foo() within GUI.py, but it is not defined yet when from GUI import * line is called from CORE.py, therefore the error.

You can move the foo definition into GUI.py for this simple case

Typically the GUI depends on the "core" modules, though, not the other way around.

Upvotes: 3

Related Questions