英語613685 views
小学社会310495 views
教育149515 views
高校日本史190578 views
いろは3011036 views
MathPython497416 views
世界の国564562 views
高校倫理1440172 views
高校国語788355 views
中学英語811754 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesLanguage Model NewsSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksCherry BlossomWater RippleWater SplashBreaking GlassGlass TextureFabric TextureWood GrainMarble TextureBrick Wall TextureMetal TextureWashi Paper TextureCardboard TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsRolling DiceCross SectionsMotion PathMechanicsWavesElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

Python の Callable による関数型の指定

Callable 型ヒントを使うと、関数を引数として受け取る関数や、関数を返す関数の型を明確に表現できます。

基本的な使い方

Callable は Callable[[引数の型], 戻り値の型] の形式で指定します。

from typing import Callable

def apply_twice(func: Callable[[int], int], value: int) -> int:
    return func(func(value))

def add_one(x: int) -> int:
    return x + 1

result = apply_twice(add_one, 5)
print(result)  # 7

複数の引数を持つ関数

引数が複数ある場合は、リストに列挙します。

from typing import Callable

def operate(func: Callable[[int, int], int], a: int, b: int) -> int:
    return func(a, b)

def add(x: int, y: int) -> int:
    return x + y

result = operate(add, 3, 4)
print(result)  # 7

引数なしの関数

引数がない場合は空のリストを使います。

from typing import Callable

def call_factory(factory: Callable[[], str]) -> str:
    return factory()

任意の引数を取る関数

引数の詳細を指定しない場合は … を使います。

from typing import Callable

def execute(func: Callable[..., None]) -> None:
    func()

デコレータの型付け

デコレータは「関数を受け取り関数を返す」ので、Callable を組み合わせて表現します。

from typing import Callable, TypeVar

F = TypeVar("F", bound=Callable[..., object])

def my_decorator(func: F) -> F:
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper  # type: ignore

Callable を活用すると、高階関数の意図がコード上で明確になります。