Python callable(): Check If an Object Is Callable — Syntax, __call__ Method, Functions vs Instances, Descriptors, Pitfalls, and Practical Examples > dev

Skip to content
Entire search within the site

dev

Python Python callable(): Check If an Object Is Callable — Syntax, __call__ M…

page info

profile_image
Author Goposu
comment 0co View 12hit Creation date 25-10-11 01:43

본문

Python callable(): Check If an Object Is Callable — Syntax, __call__ Method, Functions vs Instances, Descriptors, Pitfalls, and Practical Examples

Python callable(): Determine whether an object can be called

The built-in callable() function returns True if an object appears callable (i.e., it can be invoked with parentheses), and False otherwise. In Python, functions, methods, classes, and objects implementing __call__() are callable; typical data objects are not. This guide explains syntax, common patterns, caveats, and realistic use cases.

Syntax

callable(obj)

Parameter: Any Python object.

Returns: True if obj is callable; False otherwise.

Quick examples

def f(): pass
print(callable(f))            # True (function)

print(callable(len))          # True (built-in function)
print(callable(str))          # True (class is callable to create instances)

x = 42
print(callable(x))            # False (int is not callable)

class C:
    def __call__(self, *args, **kwargs):
        print("called")

c = C()
print(callable(c))            # True (instance with __call__)
c()                           # "called"

What counts as callable

  • Functions and methods: User-defined functions, built-ins like len, instance and class methods.
  • Classes: Calling a class constructs an instance (hence callable).
  • Objects with __call__: Any instance defining __call__() is callable and behaves like a function.
  • functools.partial and wrappers: Partially applied callables remain callable.
import functools

def add(a, b): return a + b
add5 = functools.partial(add, 5)
print(callable(add5))         # True
print(add5(3))                # 8

Common use cases

  • Plug-in hooks: Verify a provided callback is callable before invoking.
  • Factory patterns: Accept either constructor (class) or function to build objects.
  • APIs accepting callables: Schedulers, event handlers, and functional utilities.
def run(callback, *args, **kwargs):
    if not callable(callback):
        raise TypeError("callback must be callable")
    return callback(*args, **kwargs)

print(run(str.upper, "hello"))   # "HELLO"
print(run(list, "abc"))          # ["a", "b", "c"]

Pitfalls and caveats

  • Having a __call__ attribute isn’t enough: callable() uses the object’s call protocol; manually checking hasattr(obj, "__call__") can be misleading.
  • Properties and descriptors: A method accessed via an instance is callable; a property returns a value that may not be callable.
  • Modules are not callable: You import and access attributes; you don’t call modules directly.
  • NumPy arrays and pandas objects: Typically not callable unless explicitly designed to be.
  • Classes are callable, instances are not (unless __call__): Remember to check the instance, not just its type.
class WithProperty:
    @property
    def value(self): return 10
    def method(self): return 20

obj = WithProperty()
print(callable(obj.value))    # False (property returns int)
print(callable(obj.method))   # True (bound method)

Designing callable objects

Implement __call__() to make objects behave like functions. This is useful for configurable processors, stateful validators, and caching decorators.

class Scaler:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):
        return x * self.factor

scale2 = Scaler(2)
print(scale2(5))              # 10
print(callable(scale2))       # True

Testing and safety

  • Validate before invoking: Guard calls in dynamic code paths.
  • Type hints: Use typing.Callable for static checking with function signatures.
  • Error messaging: Provide clear feedback when a non-callable is supplied.
from typing import Callable

def apply(func: Callable[[int], int], x: int) -> int:
    if not callable(func):
        raise TypeError("func must be callable")
    return func(x)

FAQ

Is a class callable?
Yes. Calling a class constructs and returns an instance.
How do I make an instance callable?
Define __call__(self, ...) in the class.
Does callable() confirm the exact signature?
No. It only checks callability, not argument count or types. Validate at runtime or with type hints.
Is checking hasattr(obj, "__call__") equivalent?
Not always. Prefer callable(obj) which uses Python’s call protocol.

Related keywords

Python callable, __call__, function objects, bound methods, class constructors, callbacks, typing.Callable, factory pattern

추천0 비추천0

comment list

There are no registered comments.

Total 19건 1 page

search

memberlogin

join

Copyright © https://goposu.com All rights reserved.