python not recognizing function within imported module

Viewed 1499

I am working in Jupyter notebook. I created a simple module called conv.py for converting miles to km. When I try to import this module in a separate code (in the same directory) the import seems to go successfully but it doesn't recognize either of the functions I defined in the 'conv' module.

I have imported os and os.getcwd() provides the correct folder for conv.py...

code for conv.py

 in_n_ft = 12
 ft_n_mile = 5280
 m_n_km = 1000
 cm_n_in = 2.54
 cm_n_m = 100
 mm_n_m = 1000
 def ft_to_km(feet):
     return feet*in_n_ft*cm_n_in/cm_n_m/m_n_km
 print(ft_to_km(5280))
 def mil_to_km(mile):
     return mile*ft_n_mile*in_n_ft*cm_n_in/cm_n_m/m_n_km
    
 print(mil_to_km(3.2)) 

Code for new module

 import conv
 km = conv.mil_to_km(5) 

Error provided


AttributeError                            Traceback (most recent call last)
<ipython-input-111-bfd778724ae2> in <module>
      3 import conv
      4 
----> 5 km = conv.mil_to_km(5)
AttributeError: module 'conv' has no attribute 'mil_to_km'

When I type

dir(conv)

I get

['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

What am I doing wrong?

EDIT

I have also tried

from conv import mil_to_km

when I do that I get a different error

cannot import name 'mil_to_km' from 'conv' (C:\Users\223023441\Documents\python\conv.py)

I have also queried the module using:

from inspect import getmembers, isfunction
import conv

print(getmembers(conv, isfunction))

from here I get:

['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

I am also unable to access any of the variables within the conv.py file after import... Am I doing something wrong when I save the py file? Jupyter makes ipynb as the common file, when I 'save as' to conv.py, is this screwing it up?

2 Answers

You should import from the module. Try this:

from conv import mil_to_km

km = mil_to_km(5) 

The reason is that when you import the module in that way, you are executing it. In the way I shown, you are just importing the needed functions.

So the ultimate issue was the way I was saving the .py file... I was using the 'save as' command in jupyter notebook and typing 'conv.py' for my file save... This was showing up in the directory as a .py file, but my main file wasn't recognizing it properly. Once I downloaded the file as a .py file, cut from my downloads folder and pasted into my working directory everything worked...

Related