Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create and Import a Custom Module in Python

Tags:

python-3.x

How can I save the following function in one python file, and then use it in another?

Function in File A

def basic(x):
    print(x)

Statement in File B:

basic("some string")
like image 463
ImUniverseSE Avatar asked May 06 '16 12:05

ImUniverseSE


People also ask

How do I import a new module in Python?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.

How do you import a custom class in Python?

Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

Can we create modules in Python?

Additionally, you can create your own Python modules since modules are comprised of Python . py files. This tutorial will guide you through writing Python modules for use within other programming files.


1 Answers

A. Create a folder which will contain all of your modules. As an example, lets use 'MyModules'

Create_Directory

B. Within the folder, save your classes in a py file. You can have more nesting than I'll demonstrate, but for simplicity we will not nest folders in this example.

Classes

enter image description here

C. Create another python file in the same directory named 'init'. Note there are 2 underscores before and after 'init'. Within that file, import the file you need.

The syntax should be 'from FOLDERNAME import FILENAME'

Init Import

Init Location

D. Now, from a new python file, you can import your custom classes. Note, if your package isn't recognized, you may need to change the path you're running the file from.

import

RESULT

RESULT

like image 90
PyNoob Avatar answered Oct 06 '22 10:10

PyNoob