Create Python Library

Python Library

For Python, there are a lot of library prepared by Python (default), PyPI.

In development project, common use and team development, are required library

Structure Library

Before starting explanation, show project sturcture

LibraryProject
| - main.py  : For test
| - main2.py : For test
| - main3.py : For test
| - librarysample
      |- __init__.py
      |- tools
      |   |- __init__.py
      |   |- color.py
      |- utils
          |- __init__.py

__init__.py

Before Python 3.3, __init__.py indicates this directory is library. For compatible, use this as library directoy, but not required now.

Let’s start creating library

Condition

  • PyCharm
  • Python 3.8

Create Python project

Create Python package directory from IDE. (Python package prepares __init__.py automatically)

Writing Codes

Let’s write codes, basically if __name__ == ‘__main__’: is for test, run this file with python codes can be test

tools/color.py

from termcolor import colored

def colorgreet(name):
    print(colored(f'{name}', 'red'))

if __name__ == '__main__':
    colorgreet('Taro')

if you want to test this

python3 tools/color.py

if __name__ == ‘__main__’: is to run only when we run with python command. If we use as a library, this part should be skipped. So, we can use here as test space.

tools/__init__.py

__all__ = ['color']

This is to use *(asterisk) import

utils/custom.py

def customgreeting(name, prefix):
    print(f'{prefix}, {name}')

if __name__ == '__main__':
    customgreeting('Good evening', 'Jiro')

utils/util.py

def greeting(name):
    print(f'Hello, {name}')

if __name__ == '__main__':
    greeting('Saburo')

utils/__init__.py

__all__ = ['custom', 'util']

Prepared all, let’s use from outside of library

Use this library

Create 2 patterns of test

main.py

from librarysample.tools import color
from librarysample.utils import custom
from librarysample.utils import util

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    color.colorgreet('Jun')
    custom.customgreeting('Mr. Bean', 'Good Afternoon')
    util.greeting('Sun')

Use “from” description. from <libraryname(directory)>.<directoryname> import <filename>

To call this, <filename>.<methodname>

main2.py

from librarysample.tools import *
from librarysample.utils import *

if __name__ == '__main__':
    color.colorgreet('Ming')
    custom.customgreeting('Masa', 'Hello')
    util.greeting('Mona')

Create library tar.gz

To deploy somewhere (or PyPI), we need to create tar.gz, Pycharm prepares setting for this from IDE operation. (setup.py)

Create setup.py

setup.py is required file to explain library details.

“Tools” -> “Create setup.py”

Please fill description, version, License etc… Can skip some parameters (skip author email, show warning!!)

Next, you need to run setup.py

“Tools” -> “Run setup.py Task”

Run setup.py and generate files

You can see library under dist/

コメント

タイトルとURLをコピーしました