PyObjC CoreML Framework
PyObjC-framework-CoreML provides Python wrappers for Apple's CoreML framework on macOS, enabling Python applications to interact with Core ML models. It is part of the larger PyObjC project, which creates a bridge between Python and Objective-C, and is actively maintained with releases often aligned with macOS updates. The current version is 12.1.
Warnings
- breaking PyObjC 12.0 dropped support for Python 3.9. Users must ensure their environment uses Python 3.10 or later. PyObjC 11.0 also dropped support for Python 3.8.
- breaking PyObjC 11.1 aligned its memory management behavior for `init` methods with `clang`'s Automatic Reference Counting (ARC). Methods in the `init` family now correctly steal a reference to `self` and return a new one. This change might affect code relying on previous PyObjC reference counting behavior for initializers.
- gotcha In PyObjC 10.3, a change broke the ability to use Python's `__init__` when a user also implements `__new__` for an Objective-C subclass. While 10.3.1 partially re-introduced this, classes relying on `__new__` provided by PyObjC still cannot use `__init__`.
- breaking The `IMServicePlugIn` bindings were completely removed in PyObjC 10.0. This framework was deprecated by Apple in macOS 10.13 and removed in macOS 14.
- gotcha While PyObjC 11.0 introduced *experimental* support for free-threading (`PEP 703`) with Python 3.13, PyObjC 10.3 explicitly stated it does *not* support experimental free-threading in Python 3.13. Users should exercise caution and thoroughly test when using free-threading with PyObjC, especially with specific framework bindings.
Install
-
pip install pyobjc-framework-coreml
Imports
- CoreML
import CoreML
- MLModel
from CoreML import MLModel
Quickstart
import CoreML
import Foundation # Often needed for NSURL, NSBundle etc.
import os
# --- This example demonstrates attempting to load a CoreML model ---
# In a real scenario, 'your_model.mlmodel' would be a path to an actual Core ML model file.
# For demonstration, we'll try a dummy path or look for a model in the app bundle.
# Replace with the actual path to your .mlmodel file or ensure it's in your app bundle.
# Option 1: Direct path (replace with actual path)
model_path = os.environ.get('COREML_MODEL_PATH', '/tmp/your_model.mlmodel')
# Option 2: Attempt to find in the main bundle (common for macOS apps)
# mainBundle = Foundation.NSBundle.mainBundle()
# model_path_from_bundle = mainBundle.pathForResource_ofType_("YourModelName", "mlmodel")
# if model_path_from_bundle:
# model_path = model_path_from_bundle
print(f"Attempting to load CoreML model from: {model_path}")
try:
# CoreML methods often follow Objective-C conventions, e.g., 'methodName_error_'
# for methods that take an NSError** parameter in Objective-C.
# The PyObjC bridge translates this into a tuple (result, error_object).
model, error = CoreML.MLModel.modelWithContentsOfURL_error_(
Foundation.NSURL.fileURLWithPath_(model_path), None
)
if error:
print(f"Error loading model: {error.localizedDescription()}")
elif model:
print(f"Successfully loaded CoreML model: {model}")
print(f"Model description: {model.modelDescription()}")
# You can now interact with the model, e.g., for predictions:
# input_features = CoreML.MLFeatureProvider.alloc().init()
# prediction, pred_error = model.predictionFromFeatures_error_(input_features, None)
# if not pred_error: print(f"Prediction: {prediction}")
else:
print("Failed to load model without explicit error or model object.")
except Exception as e:
print(f"An unexpected Python exception occurred: {e}")
print(f"\nAccessing MLModel class directly: {CoreML.MLModel}")