0

I have two files: 'my_main.py' and 'my_functions.py'. I wrote two functions in 'my_functions.py', 'first_function' and 'second_function' and imported this module into 'my_main.py'. However, I then added a third function into 'my_functions.py' called 'third_function':

def first_function():
    print("hello1")

def second_function():
    print("hello2")

def third_function():
    print("hello3")

I found that I could not import 'third_function' into 'my_main.py', getting an error - AttributeError: module 'my_functions' has no attribute 'third_function'.

To understand this, in 'my_main.py' I then ran:

import my_functions
help(my_functions)

and had as my output:

Help on module my_functions:

NAME
my_functions

FUNCTIONS
first_function()

second_function()

For some reason 'my_functions.py' would not recognise any more functions after the initial two, meaning I couldn't then import 'third_function' into 'my_main.py'. How can I fix this?

  • 1
    Does your file with your functions actually look like that? Python requires you to indent. If it looks like that i'm surprised it runs at all. – Cfreak Jan 18 '19 at 17:32
  • Not sure if this is a similar case, but at least in Jupyter Notebook, updates to a module are not loaded unless I kill the kernel and start over (probably a cache issue) – Tacratis Jan 18 '19 at 17:33
  • I've just restarted the kernel and re-run the program and it seems to have fixed it. Thanks, thought it was a more complex issue than that! – Jordan Bartlam Jan 18 '19 at 17:40
  • Which ide you use btw ? – sahasrara62 Jan 18 '19 at 17:40

2 Answers2

0

Make sure you have saved your file my_functions.py before running my_main.py. Unless the file is saved, the update (addition of third_function) won't be recognized. Have been doing this for years, and still make this mistake constantly. Editing not enough. Need to edit and save.

Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
0

You need to explicitly reload the module if you've made changes since the last import. There is a built-in function for this

You can reload your module as follows:

import importlib
importlib.reload(my_functions)

See this answer for a much more detailed explanation.

Luke G
  • 23
  • 1
  • 6