1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonメモ

Last updated at Posted at 2025-07-24

基本

標準エラー出力

import sys
print("hello, world", file=sys.stderr)
# hello, world

Noneチェック

面倒くさがって省略して書くと 0 が抜けてしまう。

for value in [None, 0, 123, 999]:
    if value:
        print(value)
# 123
# 999

ちゃんと is / is not で調べましょう。

for value in [None, 0, 123, 999]:
    if value is not None:
        print(value)
# 0
# 123
# 999

ただし、str型のときは空チェックも出来て便利だったりする。

for value in [None, "", "0", "123", "999"]:
    if value:
        print(value)
# 0
# 123
# 999

enum

Enum

  • Enum の基本的な定義
  • クラスメソッドの実装
  • __str__() の実装
  • 型ヒントの前方参照
from __future__ import annotations
from enum import Enum, auto
from typing import Iterable

class Color(Enum):
    NONE = auto()
    RED = auto()
    BLUE = auto()
    YELLOW = auto()

    # 文字列からenum生成
    @classmethod
    def parse(cls, string: str) -> Color:
        try:
            return cls[string.upper()]
        except (KeyError, AttributeError):
            return cls.NONE

    # C言語用のテーブル
    @classmethod
    def format_as_c_array(cls, colors: Iterable[Color]) -> str:
        return f"{{ {", ".join(str(color) for color in colors)} }}"

    def __str__(self) -> str:
        return f"{self.__class__.__name__}_{self.name}"

colors = [Color.parse(color) for color in ["red", "blue", "yellow", "green"]]
print(colors)
# [<Color.RED: 2>, <Color.BLUE: 3>, <Color.YELLOW: 4>, <Color.NONE: 1>]
print(Color.format_as_c_array(colors))
# { Color_RED, Color_BLUE, Color_YELLOW, Color_NONE }

xmltodict

要素が空でも一つでもリストで返す

force_list 使わない

import xmltodict

xml = xmltodict.parse("""
<Data>
    <Values1>
        <Value>100</Value>
        <Value>200</Value>
        <Value>300</Value>
    </Values1>
    <Values2>
        <Value>999</Value>
    </Values2>
    <Values3 />
</Data>
""")

# そのまま
try:
    print(xml["Data"]["Values1"]["Value"])  # ['100', '200', '300']
    print(xml["Data"]["Values2"]["Value"])  # 999
    print(xml["Data"]["Values3"]["Value"])  # 'NoneType' object is not subscriptable
except Exception as e:
    print(e)

# 関数かます
def values(dic, key):
    return (values if isinstance(values := dic[key], list) else [values]) if dic else []

print(values(xml["Data"]["Values1"], "Value"))  # ['100', '200', '300']
print(values(xml["Data"]["Values2"], "Value"))  # ['999']
print(values(xml["Data"]["Values3"], "Value"))  # []

force_list 使う

羅列出来るよう規模なら使うかも。

import xmltodict

xml = xmltodict.parse("""
(略)
""", force_list=("Value"))

# そのまま
try:
    print(xml["Data"]["Values1"]["Value"])  # ['100', '200', '300']
    print(xml["Data"]["Values2"]["Value"])  # ['999']
    print(xml["Data"]["Values3"]["Value"])  # 'NoneType' object is not subscriptable
except Exception as e:
    print(e)

# 関数かます
def values(dic, key):
    return dic[key] if dic else []

print(values(xml["Data"]["Values1"], "Value"))  # ['100', '200', '300']
print(values(xml["Data"]["Values2"], "Value"))  # ['999']
print(values(xml["Data"]["Values3"], "Value"))  # []
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?