-1

I have been attempting to define a python function in one script (lets call it script1.py) like so:

def fn1(): 
 print("Hello")

and then to import it into a separate python file in the same directory (lets call it script2.py) like this:

from script1 import fn1 or import script1

I've found lots of posts/answers supporting this process, but I continue to receive the error message that there is "No module named 'script1'". Most of the posts I've seen are from 3+ years ago, so perhaps the newer versions of python have terminated this option.

I appreciate any solutions!

Brad Figueroa
  • 869
  • 6
  • 15
jros
  • 387
  • 2
  • 15

1 Answers1

1

If your two files are in the same folder, you can try adding a blank __init__.py file to your folder and using a relative import:

from .script1 import fn1

Adding the '.' before the module name ensures that your script is looking in the current directory.

To specify the parent directory, try: from {folder_name}.script1 import fn1 where folder_name is parent directory

You can read more about relative imports in Python 3 documentation.

jros
  • 387
  • 2
  • 15
lawndoc
  • 80
  • 7
  • I've tried this, but received the error message "attempted relative import with no known parent package", do you gave any suggestions on how to specify the parent package? – jros Jul 12 '21 at 20:30
  • I edited my comment, you can mark the directory as a module by creating a blank \_\_init\_\_.py file in the same folder – lawndoc Jul 12 '21 at 20:32
  • I have added the blank __init__.py file to the folder and am running the import in script2.py without any success, I appreciate the efforts, any other ideas? – jros Jul 12 '21 at 20:35
  • @jros can you try with `from {folder_name}.script1 import fn1` where folder_name is parent directory – Brad Figueroa Jul 12 '21 at 20:42
  • unfortunately not, I am however able to get the: import .script1 portion to work but importing the function is still not working – jros Jul 12 '21 at 23:53
  • @BradFigueroa I figured out I had to reference the whole path for the project to get it to work: import project1.scripts.test.script1 (If you would add that to your answer or something suggesting that idea, I'll accept your answer and close the post) Thanks! – jros Jul 13 '21 at 11:48