0

I am coding a simple game of tic-tac-toe. My function to check winning is too repetitive and big, so I want to put it into an external file. My idea is:

class Game(object):
    def __init__(self):
        pass
    import funcFile

instance = Game()
instance.func()

While in funcFile.py is:

def func():
    print("Hello world!")

But:

Traceback (most recent call last):
    instance.func()
TypeError: 'module' object is not callable

Is there a way to do this, or should I put everything in one file?

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
maximxls
  • 47
  • 1
  • 4

2 Answers2

1

There are many ways to solve this kind of problem.

The most straightforward solution (which is what I think you had in mind) is to factor out the implementation of the func method to a separate module. But you still need to define the method in the class.

main.py:

from func_module import func_implementation

class Game:  # note: you don't need (object)
    def __init__(self):
        pass

    def func(self):
        return func_implementation()

instance = Game()
instance.func()

func_module.py:

def func_implementation():
    print('hello')

Another approach would be to factor out the func method to another class which the Game class inherits. This pattern is also known as a mixin class:

main.py:

from func_module import FuncMixin

class Game(FuncMixin):
    def __init__(self):
        pass

instance = Game()
instance.func()

func_module.py:

class FuncMixin:
    def func(self):
        print('hello')

But this is less clear, as you can't immediately see that the Game class has a func method and what it does. Also you can introduce subtle bugs with multiple inheritance if you're not careful. So in your case I'd prefer the first approach.

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
0

You should try from funcFile import func in your main file:

from funcFile import func

class Game(object):
    def __init__(self):
        pass
    import funcFile

instance = Game()
instance.func()
Tariq
  • 2,369
  • 10
  • 31
  • 60
nadapez
  • 2,296
  • 1
  • 17
  • 25