/// BANGBOO BLOG ///

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31


February 11, 2021 List
Python Python on Feb 11, 2021 12:00 AM

February 11, 2021

Python Python
■import縺?from
Pythonのモジュール縺?import縺?from入門 - Qiita
Python, importの使い方・??from, as, PEP8の推奨スタイ繝?, 注諢?点など・?? | note.nkmk.me
Pythonインポート周り徹藹??理解への道 - Qiita
Pythonの相対インポートで臀??位ディレクトリ・サブディレクトリを指定 | note.nkmk.me

標準ライブラリならimport文を本臀??に書いていれば良い
 標準ライブラリ以外縺?PyPI(Python Package Index)と呼ばれる3rdパーティライブラリから
 pip(The Python Package Installer)インス繧?

import文を使って臀??記縺?3つなどをインポートし使う
 標準ライブラ繝?
 pipでインスコしたパッケー繧?
 自臀??のパッケー繧?
自臀??は大体繧?かるがそれ以藹??はどこにあるのか?
 $ python
 >>> import sys
 >>> sys.path
 でパス臀??覧が出るので探すと分かる >>> exit()縺?pythonコマンド終了
例え縺? Cloud functionsなら requrements.txt縺? google-api-python-client==3.3.2と鐔??載し
 PyPI · The Python Package Index でバージョンを探す
コード縺? from google.cloud import bigqueryと宣言する
 requirementがpipインス繧?

import フォルダ.ファイル名
from フォルダ.ファイル名 import *
 上下同じだが、fromは臀??部を指定し直接使うという諢?、*は非推螂?
 つまり
import hello なら下記とする必要があるが
 print(hello.hello)
from hello import hello なら省略ができ下記で良い
 print(hello)
from フォルダ名 の場合
 そのフォルダ名の中縺? __init__.pyがあれば其れ
from .xxx import aaa 縺?.の諢?味は・??
 mainに対するモジュールから見て相対で髫?

モジュール觸??索パスを出す
from pprint import pprint
import sys
pprint(sys.path)

■pipインス繧?
pipの使い譁? (2014/1バージョ繝?) — そこはかとな縺?書縺?よん。 ドキュメント (tdoc.info)
Python:pip における管理者権限縺? user install - pyてよn日鐔?? (hatenablog.com)
Python でパッケージを開発して配布する標準的な方觸?? - Qiita
python縺?setup.pyについてまとめる - Qiita
PyPIでサードパーティライブラリを管理していてインスコ藹??
setup.pyが含まれたローカルディレクトリも指定しインスコ藹??
eオプションで編集可能な状態でインス繧?
--user縺?~/.local下の管理権限不要なユーザディレクトリ以下でシステムが汚れない
--userなし縺?/usr下にインス繧?
pip install --user -e unko
pip3 install pipenv
pip list インスコ觸??みのものを確鐔??

pip install -r requirements.txt reqirements.txtで臀??括インス繧?
pip freeze > r.txt pip listをファイルに書き出す
pip uninstall -y -r r.txt -yで確認なしで臀??括アンインストー繝?
Python, pip縺?requirements.txtを使ってパッケージ臀??括インストー繝? | note.nkmk.me

パッケージとバージョンを指定してアップデート

■envツー繝?
 pyenv install --list インストールできるも縺?
 pyenv install 3.8.8 指定verをインス繧?
 pyenv global 3.8.8 デフォルトに指定
 .python-versionファイルをGITに鐔??せ管理したい?
 pipenv縺?Pipfile縺?Pipfile.lockを利用しpip縺?requrements.txtを用いるよりも強力
  Pipfile縺?Pipfile.lock縺?requirementsをGITに鐔??せ管理したい?
 pipenv --python 3.8.8 など最初縺?pyバージョンをpipfileに鐔??載
 pipenv install "google-cloud-tasks==1.5.0" バージョン無しでも有りでも入れられる
 Pipfileを書き觸??える方觸??
  [packages]
  google-cloud-tasks = "==1.5.0"
  protobuf = "*"
  そして臀??記cmdでインス繧?
  pipenv install PipefileからインストールしPipefile.lockを更譁?
 pipenv sync Pipfile.lockの最新を藹??得し環藹??更譁?(Pipefileは使繧?ない)
 pipenv shell 仮想環藹??を起動
 pipenv run python main.py
 他縺?
 pipenv uninstall google-cloud-tasks アンインス繧?
 Pipfile, Pipfile.lockがあれ縺? pip sync縺?OKだがrequirements.txtも使える
 pipenv lock -r > requirements.txt 生成
 pipenv install -r requirements.txt
pipenvのバージョンが古いと臀??存関臀??、Ver整合性で問題が起きやすい
 pipenv --version
 pip install pipenv
 pipenv update
 pipenv upgrade <パ繧?>でやり直す

■assertでテスト
assert文は軆??み込み藹??謨?__debug__がTrueの時のみ藹??行されます
実行コマンドにオプション縺?-Oをつける縺?__debug__がFalseになりassert文が無効縺?
def func_so(a, b):
c = a * b
return 
def test():
assert(func_so(1,2) == 2)
if __name__ == "__main__":
test()
main()

■テスト駆動
PyTest を LLMに書いてもらいたい。下記のようなプロンプトで觸??備できるので縺??
https://aaaa にアクセスし名前欄縺?aaaと入力すると名前欄に英数が入っていますとエラーが出る

■PyTest
assert
成立すべき蠑?(Trueになるべき蠑?) をassert文で鐔??霑?

テストの觸??備と藹??処理
@pytest.fixtureデコレータをつける

実行(ディレクトリ縺?test、testファイル、test 関数が対象)
pytest

テストカバレッジを確鐔??:tests/ディレクトリ内の全テストを実行し現在のディレクトリ内のコードについてどれだけテストでカバーされているかを測藹??
pytest -covs=. tests/

■test app.pyでエラー表示を拾ってテスト
import pytest
from app import app

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

def test_valid_input(client):
    response = client.post(
        '/', 
        data={'name': 'TestUser', 'email': 'Test@example.com'}, 
        follow_redirects=True
    )
    assert b'OKでっせ' in response.data

def test_invalid_name(client):
    response = client.post(
        '/', 
        data={'name': 'ThisNameIsTooLong', 'email': 'test@example.com'}, 
        follow_redirects=True
    )
    assert b'name At most 10 characters long' in response.data

def test_invalid_email(client):
    response = client.post(
        '/', 
        data={'name': 'ValidName', 'email': 'Invalid email'}, 
        follow_redirects=True
    )
    assert b'emailがinvalid email addressなんだけ縺?' in response.data


■パラメータを複数種類
import pytest
@pytest.mark.parametrize(
"x, y", [
("aaa", "bbb"),
("aaa", "aaa"),
("bbb", "bbb")
]
)
def test_1(x, y):
assert x == y

■fixture: fixture@yieldまでの処理> テスト本臀??> fixture縺?yield後からreturnまでの処理
import pytest
from pathlib import Path
import shutil

def create_file(path):
    # 指定されたパスにファイルを作成する関謨?
    path.touch()

# 一時ディレクトリを作成するフィクスチ繝?
@pytest.fixture()
def create_tmp_dir():
    # 一時ディレクトリを作成
    tmp_dir = Path("/tmp/test")
    if not tmp_dir.exists():
        tmp_dir.mkdir()
    yield tmp_dir
    # 一時ディレクトリを削髯?
    shutil.rmtree(tmp_dir)

def test_create_file(create_tmp_dir):
    target_file = create_tmp_dir / "test.txt"
    create_file(target_file)
    assert target_file.exists()


■個蛻?
import dataclasses
[詳解] Python縺?dataclasses (zenn.dev)
 データ格軆??するオブジェクトを作れば使い回しが讌?
import datetime
pip install pyyaml > import yaml
pip install requests > import requests

Python + VSCode の環藹??構築 20240604 (zenn.dev)


↓本家
/// BANGBOO BLOG /// - Python

Posted by funa : 12:00 AM | Web | Comment (0) | Trackback (0)