Home > Backend Development > Python Tutorial > How to Import and Call a Function from a Separate Python File?

How to Import and Call a Function from a Separate Python File?

Susan Sarandon
Release: 2024-11-30 13:00:15
Original
590 people have browsed it

How to Import and Call a Function from a Separate Python File?

How to Call a Function from a Different Py File

When working with multiple Python files, it's often necessary to import functions from one file into another. However, issues can arise if the imported file's name collides with a built-in Python module, as demonstrated in the example code.

file.py contains a function named function. How do I import it?

from file.py import function(a,b)
Copy after login

This code throws an "ImportError: No module named 'file.py'; file is not a package" error because "file" is a core Python module. To resolve this issue, follow these steps:

  1. Import the function from the file module:
from file import function
Copy after login
  1. Call the function using:
function(a, b)
Copy after login

Ensure that both the exporting and importing files are in the same directory for successful function import.

Alternatively, if you're encountering the same issue with a different file name (e.g., a.py and b.py), place both files in the same directory and use the following code:

import a
a.function(a, b)
Copy after login

The above is the detailed content of How to Import and Call a Function from a Separate Python File?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template