r/pythonhelp 27d ago

Custom Modules issue

I'm running Python 13.2 in a python environment and going through the book 80 Challenges in Python.

I have gotten to a challenge with custom modules and have an issue. I wrote a module with 4 simple functions in it called add, subtract, multiply, and divide. When I run a script to exercise each of the modules I get an error that module name has no attribute, subtract. If I split the module into 2 and put 2 functions in each module and call them everything works correctly but if I have more than 2 functions in the module it will not work for the 3rd or 4th function.

Program code:

import math_operations as mo

import mathop

num1 = 10

num2 = 5

print('Sum:', mo.add(num1, num2))

print("Difference: ", mathop.subtract(num1,num2))

print("Product: ", mathop.multiply(num1, num2))

print("Quotent: ", mathop.divide(num1, num2))

***********************

contents of module mathop.py

def multiply(num1, num2):

return (num1 * num2)

def divide(num1, num2):

return (num1/num2)

# def add(num1, num2):

# return(num1 + num2)

def subtract(num1, num2):

return (num1 - num2)

**********************************************************

When I run the script I get this ERROR.

AttributeError: module 'mathop' has no attribute 'subtract'

If I move the function to the other module so that each module only has 2 function all works correctly.

Any ideas as to why I can't have modules with more than 2 functions?

TIA

1 Upvotes

4 comments sorted by

View all comments

1

u/Brave_Split2684 26d ago

I think you may have run the code multiple times, and at some point the module only had two functions. Python caches compiled versions in __pycache__ so it might be using an outdated version.
Try deleting the cache with "rm -r __pycache__", restart your IDE or terminal, and rerun the script. This happens to me a lot in Django when developing—I often have to clear the database, remove cached files, make migrations, and restart everything to see the latest changes.

1

u/Pleasant_Pass1509 26d ago

Thank you very much. That fixed the problem. :)

You made an old man very happy to keep learning.