[Python] How to split and modularize files (simple, example)

[Python] How to split files and modularize

Speaking of modules, there was an image that the processing contents were complicated such as numpy, datetime, pandas, but in fact it turned out to be quite easy to make.

File split

A file (.py) in which multiple functions are written is divided into separate files and called.

** ① Cut and paste the function you want to move to another file (.py) **

** ② Call with the original file ** ʻImport filename` └ * File name does not require extension └ No need for () or (''). Not a method

** ③ Use of module ** Module name. Function name () └ Prefix the module name to the function name └ No extension (.py) required

The file created in this ** ① is a module **. The file name (excluding .py) becomes the module name. Only this.

What I was interested in If copy and paste is copy, can cut and paste be cut and pasted? (It has nothing to do with it and I have never heard of it)

## Modularization example

1. 1. File before modularization

As an example, define the following function in the file before modularization. ① Greeting function konchiwa ② Function to find dog year birthdayDog

Move these two functions to another file and load them as a module.

main.py


def konchiwa(name):
    print(f'{name}Hello!')


def birthdayDog(name, age="24"):
    print(f'{name}Mr.{age}Happy birthday to you.')
    
    dogyear = age*7
    print(f'{name}Is dog year{dogyear}I'm old')

def validate(age):
    if age<10: 
        return False
    return True
    

print('It is a program to say hello and ask for a dog year.')
name = input('Please tell me your name:')

print('---------------------------')
konchiwa(name)

age = int(input('\n Please tell me your age:'))
if validate(age):
    birthdayDog(name, age)
else:
   print('Please enter the correct age') 

2. File division (modularization)

** ▼ Split the greeting function **

hello.py


def konchiwa(name):
    print(f'{name}Hello!')

** ▼ Split the function to find the dog year **

dog.py


def birthdayDog(name, age="24"):
    print(f'{name}Mr.{age}Happy birthday to you.')
    
    dogyear = age*7
    print(f'{name}Is dog year{dogyear}I'm old')

def validate(age):
    if age<10: 
        return False
    return True

3. 3. Module loading

main.py


#Load the created module
import hello
import dog 

print('It is a program to say hello and ask for a dog year.')
name = input('Please tell me your name:')

print('---------------------------')
hello.konchiwa(name)

age = int(input('\n Please tell me your age:'))
if dog.validate(age):
    dog.birthdayDog(name, age)
else:
   print('Please enter the correct age') 

-Load: ʻimport module name -Use:module name.function name ()`


Modularization (splitting the file) simplifies the original file.

Recommended Posts

[Python] How to split and modularize files (simple, example)
[Python] Summary of how to use split and join functions
[Linux] How to subdivide files and folders
How to package and distribute Python scripts
How to split and save a DataFrame
Offline real-time how to write E11 ruby and python implementation example
How to install and use pandas_datareader [Python]
How to import CSV and TSV files into SQLite with Python
How to use functions in separate files Perl and Python versions
python: How to use locals () and globals ()
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
How to use is and == in Python
A simple example of how to use ArgumentParser
How to generate permutations in Python and C ++
Summary of how to import files in Python 3
[Python] How to read data from CIFAR-10 and CIFAR-100
How to convert SVG to PDF and PNG [Python]
How to get the files in the [Python] folder
[Python] How to use hash function and tuple.
How to plot autocorrelation and partial autocorrelation in python
How to install Python
How to install python
Python and Ruby split
[Python] [Django] How to use ChoiceField and how to add options
[Python] How to sort dict in list and instance in list
How to download files from Selenium in Python in Chrome
How to add page numbers to PDF files (in Python)
[Python] How to create Correlation Matrix and Heat Map
Python # How to check type and type for super beginners
Save lists, dictionaries and tuples to external files python
Create a simple API just to input and output JSON files ~ Python / Flask edition ~
[2020.8 latest] How to install Python
How to install Python [Windows]
python3: How to use bottle (2)
[Python] How to use list 1
How to update Python Tkinter to 8.6
How to use Python argparse
Python: How to use pydub
How to change Python version
How to develop in Python
[python] How to judge scalar
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
screen and split screen with python and ssh login to remote server
Offline real-time how to write Python implementation example of E14
How to swap elements in an array in Python, and how to reverse an array.
How to connect to various DBs from Python (PEP 249) and SQLAlchemy
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to learn TensorFlow for liberal arts and Python beginners
[Python Kivy] How to create a simple pop up window
How to upload files to Cloud Storage with Firebase's python SDK
Comparison of how to use higher-order functions in Python 2 and 3
[Python] Use this to read and write wav files [wavio]
How to write a metaclass that supports both python2 and python3
How to execute external shell scripts and commands in python
How to log in to AtCoder with Python and submit automatically