Miscellaneous notes on i2
#77
Replies: 4 comments
-
Parameter.empty behavior in function definitionsSee my relevant stackoverflow post.
Consider the two following functions: from inspect import Parameter, signature
empty = Parameter.empty
def chalk(x=empty, y=2):
return True
def cheese(x, y=2):
return TrueThe signatures (including signatures shown in help) are the same: assert signature(chalk) == signature(cheese)
assert str(signature(chalk)) == str(signature(cheese)) =='(x, y=2)'But from a parameter hints point of view (when, in a fairly rich IDE, you get hints when entering arguments in a function) they are not the same. In VsCode,
Where does signatures can lieTo see that def weirdo(a, b, c=3):
return f"{a=}, {b=}, {c=}"
assert weirdo(1, 2) == 'a=1, b=2, c=3'
# 'a=1, b=2, c=3'
weirdo.__signature__ = signature(chalk)Function's behavior doesn't change: assert weirdo(1, 2) == weirdo(1, b=2) == weirdo(a=1, b=2) == 'a=1, b=2, c=3'But the signature is different: But if we believe the More behaviorsfrom i2 import Sig
def has_valid_signature(x=Sig.empty, y=2):
return True
assert Sig(has_valid_signature) == Sig('(x, y=2)')
# Python will let me define this function
def does_not_have_valid_signature(x=2, y=Sig.empty):
return True
# But not call it:
# Sig(does_not_have_valid_signature) # Boom
# # ValueError: non-default argument follows default argument
# # TODO: we probably want to raise a InvalidSignatureError instead of a ValueError hereOn the other hand, though the following definition should be basically saying "neither x nor y have defaults", the python interpreter won't even let me define the function: def should_be_valid_but_not_parsable(x=Sig.empty, y):
pass
|
Beta Was this translation helpful? Give feedback.
-
Defaults Source ObjectI'll focus on defaults here, but it should be obvious that the same could be done with other often repeated values such as annotations, docstring argument descriptions, etc. The context that got me into the rabbit-hole writing of Parameter.empty behavior in function definitions openai_defaults = gather_defaults(list_of_objects_that_have_signatures)
# or
openai_defaults = gather_defaults(openai) # will have rules to gather the objects with signaturesThe This is what led me to writing Parameter.empty behavior in function definitions Note that such a tool would have to resolve conflicts, just like with signature merging. In fact, one way to make this object would be simply to merge all signatures of the list (after making them all be PK kind, and removing annotations, to not have any conflicts at that level). |
Beta Was this translation helpful? Give feedback.
-
Already existing (sorta) finer typesI found this: https://github.com/python/typeshed/blob/main/stdlib/_typeshed/__init__.pyi It's unfortunately not included in the standard lib itself per se, but is part of the Typeshed project, which provides type definitions for the Python standard library and third-party modules. These specific protocols (e.g., SupportsAiter, SupportsLenAndGetItem, SupportsItems, etc.) are defined in Typeshed’s internal _typeshed module, which is not a standalone importable module in the Python standard library but rather a collection of type hints used by static type checkers like Pylance, mypy, and pyright. I'm not sure how I should use them besides just copying them over to where I want to use them, but I'd rather use these than those that I have been writing myself. There's things like: ...
# Mapping-like protocols
# stable
class SupportsItems(Protocol[_KT_co, _VT_co]):
def items(self) -> AbstractSet[tuple[_KT_co, _VT_co]]: ...
# stable
class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]):
def keys(self) -> Iterable[_KT]: ...
def __getitem__(self, key: _KT, /) -> _VT_co: ...
# This protocol is currently under discussion. Use SupportsContainsAndGetItem
# instead, if you require the __contains__ method.
# See https://github.com/python/typeshed/issues/11822.
class SupportsGetItem(Protocol[_KT_contra, _VT_co]):
def __contains__(self, x: Any, /) -> bool: ...
def __getitem__(self, key: _KT_contra, /) -> _VT_co: ...
# stable
class SupportsContainsAndGetItem(Protocol[_KT_contra, _VT_co]):
def __contains__(self, x: Any, /) -> bool: ...
def __getitem__(self, key: _KT_contra, /) -> _VT_co: ...
# stable
class SupportsItemAccess(Protocol[_KT_contra, _VT]):
def __contains__(self, x: Any, /) -> bool: ...
def __getitem__(self, key: _KT_contra, /) -> _VT: ...
def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ...
def __delitem__(self, key: _KT_contra, /) -> None: ...
StrPath: TypeAlias = str | PathLike[str] # stable
BytesPath: TypeAlias = bytes | PathLike[bytes] # stable
GenericPath: TypeAlias = AnyStr | PathLike[AnyStr]
StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable
OpenTextModeUpdating: TypeAlias = Literal[
"r+",
"+r",
"rt+",
"r+t",
... |
Beta Was this translation helpful? Give feedback.
-
💡 A Problem: Balancing Flexibility and Explicitness in Data InterfacesIn software design, interfaces must navigate a subtle trade-off: they should be robust and flexible for the user, yet clear and predictable for the developer. The Conflict: Liberal Input vs. Explicit CodeOn one hand, the Robustness Principle (Postel's Law) advises us to "be conservative in what you send, and liberal in what you accept."
This flexibility eliminates annoying data preparation boilerplate and lets the user "just give it the data we have." It allows the application layer to focus on its primary concern, encapsulating data adaptation away. On the other hand, the popular mantra "Explicit is better than implicit" warns against hidden complexity. Overly flexible interfaces can lead to code that is hard to debug and maintain because the required input preparation is not immediately obvious. A Solution: A Flexible, Organized Input Adapter
castgraph is an organized system to:
This results in interfaces that are both developer-friendly and maintainable. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This is to accumulate miscellaneous notes, observations, ideas, etc.
Beta Was this translation helpful? Give feedback.
All reactions