Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid deprecated class property stacking #637

Merged
merged 4 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ unfixable = [
]
ignore-init-module-imports = true

[extend-per-file-ignores]
[lint.extend-per-file-ignores]
"instructor/distil.py" = ["ARG002"]
"tests/test_distil.py" = ["ARG001"]
"tests/test_patch.py" = ["ARG001"]
Expand Down
14 changes: 8 additions & 6 deletions instructor/function_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@

from docstring_parser import parse
from openai.types.chat import ChatCompletion
from pydantic import BaseModel, Field, TypeAdapter, create_model # type: ignore - remove once Pydantic is updated
from pydantic import BaseModel, Field, TypeAdapter, ConfigDict, create_model # type: ignore - remove once Pydantic is updated
from instructor.exceptions import IncompleteOutputException
from instructor.mode import Mode
from instructor.utils import extract_json_from_codeblock
from instructor.utils import extract_json_from_codeblock, classproperty


T = TypeVar("T")

logger = logging.getLogger("instructor")


class OpenAISchema(BaseModel):
@classmethod
@property
# Ignore classproperty, since Pydantic doesn't understand it like it would a normal property.
model_config = ConfigDict(ignored_types=(classproperty,))

@classproperty
def openai_schema(cls) -> dict[str, Any]:
"""
Return the schema in the format of OpenAI's schema as jsonschema
Expand Down Expand Up @@ -58,8 +61,7 @@ def openai_schema(cls) -> dict[str, Any]:
"parameters": parameters,
}

@classmethod
@property
@classproperty
def anthropic_schema(cls) -> dict[str, Any]:
return {
"name": cls.openai_schema["name"],
Expand Down
32 changes: 31 additions & 1 deletion instructor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@
import inspect
import json
import logging
from typing import Callable, Generator, Iterable, AsyncGenerator, Protocol, TypeVar
from typing import (
Callable,
Generator,
Generic,
Iterable,
AsyncGenerator,
Protocol,
TypeVar,
)
from openai.types.completion_usage import CompletionUsage
from anthropic.types import Usage as AnthropicUsage
from typing import Any
Expand All @@ -15,6 +23,7 @@
)

logger = logging.getLogger("instructor")
R_co = TypeVar("R_co", covariant=True)
T_Model = TypeVar("T_Model", bound="Response")

from enum import Enum
Expand Down Expand Up @@ -179,3 +188,24 @@ def merge_consecutive_messages(messages: list[dict[str, Any]]) -> list[dict[str,
)

return new_messages


class classproperty(Generic[R_co]):
"""Descriptor for class-level properties.

Examples:
>>> from instructor.utils import classproperty

>>> class MyClass:
... @classproperty
... def my_property(cls):
... return cls

>>> assert MyClass.my_property
"""

def __init__(self, method: Callable[[Any], R_co]) -> None:
self.cproperty = method

def __get__(self, instance: object, cls: type[Any]) -> R_co:
return self.cproperty(cls)
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,3 @@ typeCheckingMode = "strict"
# Allow "redundant" runtime type-checking.
reportUnnecessaryIsInstance = "none"
reportUnnecessaryTypeIgnoreComment = "error"
reportDeprecated = "warning"
jxnl marked this conversation as resolved.
Show resolved Hide resolved
21 changes: 21 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import pytest
from instructor.utils import (
classproperty,
extract_json_from_codeblock,
extract_json_from_stream,
extract_json_from_stream_async,
Expand Down Expand Up @@ -170,3 +171,23 @@ def test_merge_consecutive_messages_single():
{"role": "user", "content": [{"type": "text", "text": "Hello"}]},
{"role": "assistant", "content": [{"type": "text", "text": "Hello"}]},
]


def test_classproperty():
"""Test custom `classproperty` descriptor."""

class MyClass:
@classproperty
def my_property(cls):
return cls

assert MyClass.my_property is MyClass

class MyClass:
clvar = 1

@classproperty
def my_property(cls):
return cls.clvar

assert MyClass.my_property == 1