[PYTHON] Attempt to extend a function in the library (add copy function to pathlib)

Extends the functions in the library. The extension is like registering a function in a Python class. (Assign to a variable under a class, each instance created from that class will have the same function)

Below, as an example, the code that extends the operation method of pathlib. Add extensions such as file copy and folder tree copy functions that are not originally available.

Extended trial item:

trial.py



# -*- coding: utf-8 -*-

#Try to extend the function in the library, try to extend the operation method of pathlib

import pathlib
import shutil

# sec: main

def main():
    
    # sec:Test data preparation
    
    pathlib.Path("./test/in1/in2").mkdir(parents=True, exist_ok=True)
    pathlib.Path("./test/test.txt").write_text("0123456789")
    
    # sec:Expansion 1:Added extension of size function to get file size which is not originally
    
    path_1 = pathlib.Path("./test/test.txt")
    print("Added extension of size function:", path_1.size())

    # sec:Expansion 2:Extended copy function for folder copy that does not exist originally
    
    path_1 = pathlib.Path("./test")
    path_2 = path_1.copy("./test2")
    input("Check if the folder test2 has been created:Stopping")

    # sec:Expansion 3:Extended addition of unlink function for deleting folders that does not originally exist
    
    path_2.unlink()
    input("Check if the folder test2 has been deleted:Stopping")

    # sec:Expansion 4:Extended copy function for file copy that is not originally added
    
    path_1 = pathlib.Path("./test/test.txt")
    path_2 = path_1.copy("./test2.txt")
    input("File test2.Check if txt was created:Stopping")

    # sec:Expansion 5:Check if the unlink function of the original file deletion also works
    
    path_2.unlink()
    input("File test2.Check if txt has been deleted:Stopping")

    # sec:Expansion 6: 「/"Others"+Also added an extension to concatenate paths
    
    path_1 = pathlib.Path("./test/test.txt")
    path_2 = path_1.parent + "in1" + "in2" + "test3.txt"
    print("「+But connect the paths:", path_2)

"""Console output example:
Added extension of size function: 10
File test2.Check if txt was created:Stopping
File test2.Check if txt has been deleted:Stopping
Check if the folder test2 has been created:Stopping
Check if the folder test2 has been deleted:Stopping
「+But connect the paths: test\in1\in2\test3.txt
"""

# sec:Expansion

#Get file size
pathlib.Path.size = lambda self: self.stat().st_size #Expansion addition

#File copy / folder tree copy
def pathlib_Path_copy_ex(self, path_to):
    if self.is_file():
        shutil.copy(str(self), str(path_to))
    elif self.is_dir():
        shutil.copytree(str(self), str(path_to))
    return pathlib.Path(path_to)
pathlib.Path.copy = pathlib_Path_copy_ex #Expansion addition

#File deletion / folder tree deletion
def pathlib_Path_unlink_ex(self, *args, **argkv):
    if self.is_file():
        pathlib_Path_unlink_orig(self, *args, **argkv)
    elif self.is_dir():
        shutil.rmtree(str(self))
pathlib_Path_unlink_orig = pathlib.Path.unlink #For holding the original function
pathlib.Path.unlink = pathlib_Path_unlink_ex #Expansion addition

# 「+Connect paths with
pathlib.Path.__add__ = lambda a, b: a / b #Expansion addition

# sec: entry

if __name__ == "__main__": main()

Python developers ...

I think it would be convenient if the copy function that makes this file copy / folder tree copy is standard in the library pathlib ...

Recommended Posts

Attempt to extend a function in the library (add copy function to pathlib)
A memorandum to register the library written in Hy in PyPI
A handy function to add a column anywhere in a Pandas DataFrame
Create a function to get the contents of the database in Go
In Jupyter, add IPerl to the kernel.
Added a function to register desired shifts in the Django shift table
How to use the C library in Python
Get the caller of a function in Python
Make a copy of the list in Python
To add a module to python put in Julialang
Use the LibreOffice app in Python (3) Add library
How to Mock a Public function in Pytest
[Wagtail] Add a login page to the Wagtail project
dlopen () ltrace a function call in a shared library
Reinventing the Wheel: libMerge to merge function definitions in Bash library into ShellScript
Create a function to visualize / evaluate the clustering result
A quick introduction to the neural machine translation library
How to unit test a function containing the current time using freezegun in python
Publish / upload a library created in Python to PyPI
Add a function to tell the weather of today to slack bot (made by python)
What does the last () in a function mean in Python?
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
I also tried to imitate the function monad and State monad with a generator in Python
The story I was addicted to when I specified nil as a function argument in Go
How to debug the Python standard library in Visual Studio
How to use the __call__ method in a Python class
Add a function to heat transfer + heat input by temperature to heatrapy
I made a function to check the model of DCGAN
How to generate a query using the IN operator in Django
To return char * in a callback function using ctypes in Python
How to get the last (last) value in a list in Python
To write a test in Go, first design the interface
In omegaconf, let's pass the direct parameter file to the function
The usual way to add a Kernel with Jupyter Notebook
Let's create a function to hold down Button in Tkinter
Notes on how to use marshmallow in the schema library
Covector to think in function
Create a function in Python
Add a dictionary to MeCab
I made a function to check if the webhook is received in Lambda for the time being
Output the key list included in S3 Bucket to a file
It's faster to add than to join and extend the list, right?
[sh] How to store the command execution result in a variable
How to determine the existence of a selenium element in Python
How to get all the possible values in a regular expression
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
I wrote a function to load a Git extension script in Python
A function that measures the processing time of a method in python
[For beginners] How to register a library created in Python in PyPI
[Python3] Define a decorator to measure the execution time of a function
I made a command to display a colorful calendar in the terminal
[Beginner memo] How to specify the library reading path in Python
How to use the render function defined in .mako (.html) directly in mako
[Python] A simple function to find the center coordinates of a circle
[Rails 6] Embed Google Map in the app and add a marker to the entered address. [Confirmation of details]
I tried to understand the learning function in the neural network carefully without using the machine learning library (second half).
I want to load the pytest fixture as a library somewhere else (pytest may not exist in the environment)
How to copy and paste the contents of a sheet in Google Spreadsheet in JSON format (using Google Colab)
Programming to fight in the world ~ 5-1