Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import function from another file

I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.

My hotel_helper.py file:

def demo1():
    print('\n\n trying to import this function ')

My other file:

from hotel.helpers.hotel_helper import demo1

demo1()

but I get:

ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'

When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.

like image 751
Shubham Devgan Avatar asked Nov 20 '25 11:11

Shubham Devgan


1 Answers

If you filename is hotel_helper.py you have to options how to import demo1:

You can import the whole module hotel_helper as and then call your func:

import hotel_helper as hh
hh.demo1()

You can import only function demo1 from module as:

from hote_helpers import demo1
demo1()
like image 73
Porada Kev Avatar answered Nov 22 '25 23:11

Porada Kev