function get_method_owner
Extracts and returns the instance object that owns a given bound method, handling both regular methods and partial functions.
/tf/active/vicechatdev/patches/util.py
564 - 570
simple
Purpose
This utility function is designed to retrieve the instance (self) that a method is bound to. It's particularly useful in introspection scenarios where you need to access the object that owns a method. The function handles edge cases like functools.partial objects by unwrapping them first to get the underlying function before accessing the __self__ attribute.
Source Code
def get_method_owner(method):
"""
Gets the instance that owns the supplied method
"""
if isinstance(method, partial):
method = method.func
return method.__self__
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
method |
- | - | positional_or_keyword |
Parameter Details
method: A bound method or functools.partial object wrapping a bound method. This should be a callable that has been bound to an instance (has a __self__ attribute). For partial objects, the function will unwrap to access the underlying method first.
Return Value
Returns the instance object (self) that owns the supplied method. This is obtained via the __self__ attribute of the method. The return type depends on the class of the instance that owns the method. If the method is a partial, it first unwraps to get the underlying function before returning its owner.
Dependencies
functools
Required Imports
from functools import partial
Usage Example
from functools import partial
class MyClass:
def my_method(self):
return 'Hello'
# Create an instance
obj = MyClass()
# Get the bound method
bound_method = obj.my_method
# Get the owner instance
owner = get_method_owner(bound_method)
print(owner is obj) # True
# Works with partial functions too
partial_method = partial(obj.my_method)
owner_from_partial = get_method_owner(partial_method)
print(owner_from_partial is obj) # True
Best Practices
- Only use this function with bound methods (methods that have been called on an instance). Unbound methods or regular functions will raise an AttributeError.
- The function assumes the method has a __self__ attribute. Ensure the input is a bound method or a partial wrapping a bound method.
- This is primarily useful for introspection and metaprogramming scenarios where you need to access the instance from a method reference.
- Be aware that this will fail on static methods or class methods that don't have a __self__ attribute pointing to an instance.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function callable_name 44.1% similar
-
function get_logger_v1 34.9% similar
-
function get_user_name 34.6% similar
-
function is_param_method 32.4% similar
-
function get_logger 32.2% similar