1

I have a ex.py file, where i defined several functions. Now, I'm trying to import ex.py to another sorter.py file as a module to use those functions.

So, inside of sorter.py, I have:

import ex
function_name()

NameError: name 'function_name' is not defined

So, I suppose, i don't have ex.py imported to sorter.py

Both .py files are in the same directory, which is not childdir for python or sublime installation folder. I tried to insert the path to ex.py into sys.path, but that didn't help. How can i fix that, considering, that I'm using sublime text editor?

OdatNurd
  • 21,371
  • 3
  • 50
  • 68

4 Answers4

1

You should simply use:

ex.function_name()
simonarys
  • 55
  • 1
  • 6
1

To use functions defined in ex.py you either need to import them directly:

from ex import function_name()
from ex import *

Or refer to the function as a part of ex:

ex.function_name()
JaHoff
  • 196
  • 5
1

Firstly check if they are located in the same folder in the memory. then you have to options:

import ex
ex.function_name()

--OR--

from ex import function_name
function_name()

You can also import everything from ex and then you won't have to right ex.Sample_Funtion. This can be done by:

from ex import *
#imports everything

function_name()
another_function_in_ex()
  • Don't forget what the [Style Guide for Python Code says about wildcard imports](https://www.python.org/dev/peps/pep-0008/#imports): "Wildcard imports (`from import *`) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools." – Matthias Jan 05 '21 at 10:26
  • Agreed. We should only follow this practice only when we are explicitly using another class in our code, then these types of imports can be helpful. – jimmie_roggers Jan 05 '21 at 10:27
1

You can simply import function_name from ex file and call it:

from ex import function_name
function_name()
ad0min
  • 11
  • 2
  • Hi ad0min. Great choice to start with Python if you might want to go further https://www.w3schools.com/python/python_modules.asp #welcomeonboard – philippeko Jan 05 '21 at 11:24