Calling in functions in another function - python

I created a function to read in a csv file and then write some of the data from the csv file into another file. I had to manipulate some of the data in the original csv file before I write it. I will probably have to do that manipulation a lot during the next couple months so I wrote another function to just do that manipulation, but I am having trouble calling in the function in my other function.
this is the function I am trying to call in:
import sys
import math
def convLatLon(measurement): # should be in '##.####' format
tpoint=float(measurement)
point_deg=math.floor(measurement) # find the degree for lat and lon
dpoint=tpoint-point_deg #subtract the lat value from just the degs to get the decimal fraction
pointmin=dpoint * 60 # find the degree mins
npoint= str(point_deg) + str(pointmin)
print(npoint)
How do I call in this function in another function? They are currently in the same directory. I am used to Matlab and thought it would be a simple call in command but I can not seem to figure it out. Any help will be greatly apprectiated.
Shay

You can import the file (same as you imported sys and math). If your function is in a file called util.py:
import util
util.convLatLon(37.76)
If the file is in another directory, the directory must be in your PYTHONPATH.

Is:
from <filename> import convLatLon
What you're looking for?

Sounds like you need to import the file.
If your function is defined in file myfile.py and you wan`t to use it from myotherfile.py, you should import myfile.py, like this:
import myfile
and then you can use the function like this:
result = myfile.myfunc(myparms)
If you want to get rid of the myfile prefix, import it like this:
from myfile import myfunc

If you have this function saved in a file called myconv.py
from myconv.py import convLatLon
convLatLon("12.3456")

Related

I'm making the snake game in Python3 and keep getting this Error: name 'Tk' is not defined what should I do? [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 6 months ago.
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
First, import function from file.py:
from file import function
Later, call the function using:
function(a, b)
Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.
Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.
Do not write .py when importing.
Let file_a.py contain some functions inside it:
def f():
return 1
def g():
return 2
To import these functions into file_z.py, do this:
from file_a import f, g
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py, then following way you can do it:
Define import statement in Example3.py - file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
Method 1. Import the specific function(s) you want from file.py:
from file import function
Method 2. Import the entire file:
import file as fl
Then, to call any function inside file.py, use:
fl.function(a, b)
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1
Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2
Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
To fix
ModuleNotFoundError: No module named
try using a dot (.) in front of the filename to do a relative import:
from .file import function
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
import module
module.function_name()
or
import pizza
pizza.pizza_function()
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
from pizza import pizza_function
pizza_function()
or
from pizza import pizza_function as pf
pf()
or
from pizza import *
pizza_function()
First save the file in .py format (for example, my_example.py).
And if that file have functions,
def xyz():
--------
--------
def abc():
--------
--------
In the calling function you just have to type the below lines.
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200
You don't have to add file.py.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Solution1: In one file myfun.py define any function(s).
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
In the other file:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
Solution2: if this above solution did not work for Colab
Create a foldermyfun
Inside this folder create a file __init__.py
Write all your functions in __init__.py
Import your functions from Colab notebook from myfun import *
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py
in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py i have import my function with below syntax
from modules.passwordGen import passGen
Just a quick suggestion,
Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.
Just change the file name from where you want to import by:
right-clicking on the file and clicking on refactor-> rename.
Your auto-import option will start coming up

Importing class from another script in tkinter GUI

I'm trying to import a class from another script so I can run the class when a button is clicked in tkinter.
The line of code I'm trying to run is:
from tkinter import *
import originalscript as desiredclass
variable = desiredclass()
When I try to run my code, the second line gives me an 'invalid syntax' error.
The two files are in the same folder and I've looked at other threads regarding this problem, but most of them suggest this as the solution, however, this line is not working for me, so I'm wondering what I am doing wrong/what I am missing?
The error code is:
Syntax Error: invalid syntax: filepath.py, line 2, pos 10
import script as class
UPDATE:
from you update to your question it looks like you may be trying to import the file as a class. Instead of doing:
variable = desiredclass()
Try this:
variable = desiredclass.ClassNameInFile()
There are several ways you might wish to import your own files.
For example if your file structure looks like this:
--Workfolder
--Main.py
--other.py
You may want to import something like this.
import other
Or if you want only something specific from that file do:
from other import func_name
However if it is part of a package you sometimes need to specify the package name first.
So if your file structure is like this:
--Workfolder
--MY_PACKAGE
--Main.py
--other.py
You may want to import like this:
import MY_PACKAGE.other
or for a specific function:
from MY_PACKAGE.other import func_name
Let me know if you have any questions.

Python calling a function from another file - error

I am attempting to call a function from another file called 'run_ES_15M_Trend_Identifier':
import sys
import os
sys.path.append(os.path.abspath(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Individual Trading\ES"))
from ES_15M_Trend_Identifier import run_ES_15M_Trend_Identifier
So the above function comes from the ES_15M_Trend_Identifier py file. I just ran that file from its own directory and it works perfect - modifies the dataframe, sends to csv. So the error isn't coming from the function itself. Instead I get the error:
ImportError: cannot import name run_ES_15M_Trend_Identifier
I realize there might be something circular about this process from other SO posts, but I'm not sure how to fix it.
edit: I've also tried:
from ES_15M_Trend_Identifier import *
run_ES_15M_Trend_Identifier()
which gives the error:
NameError: name 'run_ES_15M_Trend_Identifier' is not defined
edit: Here's the function, which works when I run it in its own file:
def run_ES_15M_Trend_Identifier():
# Do stuff to pandas dataframe, including some for loops that fill out additional columns - this function works on the original file
path_to_csv = "C:\\Users\\cost9\\OneDrive\\Documents\\PYTHON\\Daily Tasks\\Individual Trading\\ES\CSV\\15M\\Trend_Identifier\\ES_15M_Summary.csv"
ES_15M_Summary_Reduced.to_csv(path_or_buf = path_to_csv)
Is both files are in the same directory? if not put both files in the same folder!

How do I call a function from another .py file? [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 6 months ago.
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
First, import function from file.py:
from file import function
Later, call the function using:
function(a, b)
Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.
Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.
Do not write .py when importing.
Let file_a.py contain some functions inside it:
def f():
return 1
def g():
return 2
To import these functions into file_z.py, do this:
from file_a import f, g
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py, then following way you can do it:
Define import statement in Example3.py - file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
Method 1. Import the specific function(s) you want from file.py:
from file import function
Method 2. Import the entire file:
import file as fl
Then, to call any function inside file.py, use:
fl.function(a, b)
Note: If you are working with Jupiter notebook you may need to change path for method 1. :
os.chdir('/')
see https://stackoverflow.com/a/35665295/1984636
And for method 2:
import sys
sys.path.append('../src/')
see https://stackoverflow.com/a/55623567/1984636
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1
Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2
Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
To fix
ModuleNotFoundError: No module named
try using a dot (.) in front of the filename to do a relative import:
from .file import function
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
import module
module.function_name()
or
import pizza
pizza.pizza_function()
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
from pizza import pizza_function
pizza_function()
or
from pizza import pizza_function as pf
pf()
or
from pizza import *
pizza_function()
First save the file in .py format (for example, my_example.py).
And if that file have functions,
def xyz():
--------
--------
def abc():
--------
--------
In the calling function you just have to type the below lines.
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200
You don't have to add file.py.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Solution1: In one file myfun.py define any function(s).
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
In the other file:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
Solution2: if this above solution did not work for Colab
Create a foldermyfun
Inside this folder create a file __init__.py
Write all your functions in __init__.py
Import your functions from Colab notebook from myfun import *
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py
in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py i have import my function with below syntax
from modules.passwordGen import passGen
Just a quick suggestion,
Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.
Just change the file name from where you want to import by:
right-clicking on the file and clicking on refactor-> rename.
Your auto-import option will start coming up

How to include external Python code to use in other files?

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?
So if I have:
[Math.py]
def Calculate ( num )
How do I call it like this:
[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
Just write the "include" command :
import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
#Deleet :
#bfieck remark is correct, for python 2 and 3 compatibility, you need either :
Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))
If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.
I've found the python inspect module to be very useful
For example with teststuff.py
import inspect
def dostuff():
return __name__
DOSTUFF_SOURCE = inspect.getsource(dostuff)
if __name__ == "__main__":
dostuff()
And from the another script or the python console
import teststuff
exec(DOSTUFF_SOURCE)
dostuff()
And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.
It's easy and simple:
you can just do this:
def run_file(path):
return exec(open(path).read());
run_file("myfile.py");
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5.
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
I prefer Alternative #2 and have been using it in my website development.

Categories

Resources