在 Python 中檢測「是否為字符串」看似簡單,實則涉及類型體系、繼承鏈、鴨子類型哲學與歷史遺留類別。本文對比 isinstance、type、鴨子類型檢測三大流派,並深入分析 UserString 兼容性問題。
# Python 3 類型層級
str # 內建字符串類 (唯一)
bytes # 位元組序列
# 歷史遺留 (collections 模組)
from collections import UserString # 可變字符串包裝器
def is_string(obj):
return isinstance(obj, str)
# Python 2 寫法 (兼容 str/unicode)
# basestring = (str, unicode) 抽象基類
# isinstance(obj, basestring)
def is_exact_str(obj):
return type(obj) is str
is_exact_str('hello') # True
is_exact_str(StringSubclass()) # False (子類也被拒絕)
def is_string_like(obj):
"""鴨子類型:走起來像鴨、叫起來像鴨,就是鴨"""
try:
obj.lower() + obj + ' ' # 嘗試字符串典型操作
except (AttributeError, TypeError):
return False
else:
return True
# 測試
class FakeStr:
def __init__(self, s): self._s = s
def lower(self): return self._s.lower()
def __add__(self, other): return self._s + other
is_string_like('hello') # True
is_string_like(FakeStr('world')) # True (鴨子類型通過)
is_string_like(123) # False
is_string_like(b'bytes') # False (bytes 無 lower)
from collections import UserString
us = UserString('abc')
print(isinstance(us, str)) # False ❌
print(type(us)) #
print(is_string_like(us)) # True ✅ (鴨子類型通過)
# UserString 實際繼承鏈
print(UserString.__mro__)
# (UserString, collections.abc.Sequence, collections.abc.Reversible,
# collections.abc.Container, collections.abc.Iterable, object)
from collections.abc import Sequence
def is_string_abc(obj):
"""識別字符串與字符串序列 (含 UserString, bytearray 等)"""
return isinstance(obj, Sequence) and not isinstance(obj, (bytes, bytearray, memoryview))
# 更精確:僅文本序列
from typing import Union
def is_text_sequence(obj) -> bool:
return isinstance(obj, (str, UserString))
isinstance(obj, str) — 標準、快速、符合 LSPisinstance(obj, (str, UserString)) 或鴨子類型Protocol (Python 3.8+) 或 ABCtype(obj) is str
try:
basestring # Python 2
except NameError:
basestring = str # Python 3
def is_string_py23(obj):
return isinstance(obj, basestring)
import timeit
obj = 'test' * 1000
timeit.timeit('isinstance(obj, str)', globals=globals()) # ~50ns
timeit.timeit('type(obj) is str', globals=globals()) # ~40ns
timeit.timeit('hasattr(obj, "lower")', globals=globals()) # ~80ns
# 差異微乎其微,優先考慮正確性
理解字符串類型體系的邊界,能讓你在設計 API 參數驗證、序列化協議、插件系統時,做出兼容性與嚴格性平衡的正確選擇。