Call a Function from Another File

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

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.

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

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.

Python Calling Function from Another File

Let us have two files in the same directory. Files are called main.py and another.py.

First write a method in another.py:

def do_something():
return "This is the do something method"

Then call the method from main.py. Here is the main.py:

import another
print another.do_something()

Run main.py and you will get output like this:

This is the do something method

N.B.: The above code is being executed using Python 2.7 in Windows 10.

How to call functions from another file in python

Unlike java, you don't have to use classes in python. If a class is used only as a holder for functions, chances are that you want a free function (one without a class) instead.

But to answer your actual question, you can use the import statement. That will run the other .py file, and make the namespace available so you can call things defined there.

functions.py:

import json

class Functionalities:
def addelement(element):
# code goes here`

main.py:

import functions
f = functions.Functionalities()
f.addelement('some element')

Call function from another file without import clause?

Without any importing this is not possible, but what you can do is, import a module, and call a function of a submodule of that module. Like this:

import tmpapp
def kakikomi(request):
f = tmpapp.forms.KakikomiForm()

How do I call a function from another file?

Try to use

const { getAllProduct } = require('../helpers/product-helpers');


Related Topics



Leave a reply



Submit