-2

I am running the python interpreter from the same directory where the imported file my_module.py resides. When I try to use the function defined in the imported file using only the function name print_hi, I get a NameError error message. But it works fine if I reference the function using my_module.print_hi

Is there a way to make this work without referencing the module file name?

Is there a way to make this work without using the from keyword in the import statement?

PS C:\Users\joe\Documents\Python\General\importing> type my_module.py
def print_hi(name):
    print(f'Hi, {name}')
PS C:\Users\joe\Documents\Python\General\importing> python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_module
>>> print_hi('joe')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'print_hi' is not defined
>>> my_module.print_hi('joe')
Hi, joe
>>>
stackoverflowpro
  • 428
  • 2
  • 6
  • 12
  • 1
    Wouldn't a from import solve your problem: `from my_module import print_hi` or the all import (not recommended) `from my_module import *` ? – Sylvaus Sep 17 '20 at 12:06
  • It does solve the problem, but I wounder why the ```import```statement without the ```from``` keyword does not work – stackoverflowpro Sep 17 '20 at 12:26
  • Does this answer your question? [How do I import other Python files?](https://stackoverflow.com/questions/2349991/how-do-i-import-other-python-files) – gre_gor Aug 19 '23 at 17:35

2 Answers2

1

If you want to refer to your print_hi function without using the module name, you must import it explicitly or import everything from the module:

from my_module import print_hi
# or import everything:
from my_module import *
Michael Anckaert
  • 853
  • 8
  • 12
1

You can use from keyword

from my_module import print_hi
print_hi('Joe')

From is used to import only a specified section from a module.

Dragon
  • 11
  • 2