Python how to call a method from another module inside a class method

Viewed 71

So I have two files such that

# functions.py
#I have a suspicion this 2 way import might be an issue
from models import *

def foo():
    return 'bar'

def some_other_unrelated_foo():
    users = User.query.all()
    return users

and

#models
from functions import *

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(), unique=True)

    def name_and_foo(self):
        return self.username + foo()

But if I try:

print(user_a.name_and_foo())

I get the error:

NameError: name 'foo' is not defined

If instead i have one file:

#models

def foo():
    return 'bar'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(), unique=True)

    def name_and_foo(self):
        return self.username + foo()

I get the correct:

print(user_a.name_and_foo())
result: "user_abar"

What is the correct way to have the functions from functions.py visible to the class methods in models.py?

2 Answers

You have to call the function first.

#models
from functions import *

class User(UserMixin, db.Model):
    foo = foo()
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(), unique=True)

    def name_and_foo(self):
        return self.username + foo()

Make sure your files are in the same place though, that can also be the problem at time

OK I solved this shortly after posting, I moved the imports to the bottom of both files for each other and this seems to solve it. I am not 100% clear on why this works tho.

Related