Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.
...str() built-in follows: def str(s): """Return a nice string representation of the object. The return value is a str or unicode instance. """ if type(s) is str or type(s) is unicode: return s r = s.__str__() if not isinstance(r, (str, unicode)): raise TypeError('__str__ returned non-string') return r The following function would be added to the C API and would be the equivalent to the str() built-in (ideally it be called PyObject_Str, but changing th...
...str(container) calls repr on items instead of str. It's only logical to expect following code: class Test: def __str__(self): return "STR" def __repr__(self): return "REPR" test = Test() print(test) print(repr(test)) print([test]) print(str([test])) to print: STR REPR [STR] [STR] where it actually prints: STR REPR [REPR] [REPR] Especially it is illogical to see that print in Python 2 uses str if it is called on what seems to be a tuple: >>> print Decim...
...string: LiteralString s: str = literal_string # OK literal_string: LiteralString = s # Error: Expected LiteralString, got str. literal_string: LiteralString = "hello" # OK Addition of literal strings: def expect_literal_string(s: LiteralString) -> None: ... expect_literal_string("foo" + "bar") # OK expect_literal_string(literal_string + "bar") # OK literal_string2: LiteralString expect_literal_string(literal_string + literal_string2) # OK plain_string: str expect_literal_string(li...
...str][str]. However it allows e.g. dict[str, T][int] and in that case returns dict[str, int]. This design means that it is possible to create instances of parameterized collections, like: >>> l = list[str]() [] >>> list is list[str] False >>> list == list[str] False >>> list[str] == list[str] True >>> list[str] == list[int] False >>> isinstance([1, 2, 3], list[str]) TypeError: isinstance() arg 2 cannot be a parameterized generic >>>...
...Strs = Union[Tuple[str], Tuple[str, str]] def func(val: OneOrTwoStrs): if is_two_element_tuple(val): reveal_type(val) # Tuple[str, str] ... else: reveal_type(val) # OneOrTwoStrs ... if not is_two_element_tuple(val): reveal_type(val) # OneOrTwoStrs ... else: reveal_type(val) # Tuple[str, str] ... Backwards Compatibility Existing code that does not use this new functionality will be unaffected. Notably, code...
...stract Motivation Rationale Specification Backwards Compatibility Copyright Abstract Update the repr(), str(), and format() of the various Enum types to better match their intended purpose. For example, IntEnum will have its str() change to match its format(), while a user-mixed int-enum will have its format() match its str(). In all cases, an enum's str() and format() will be the same (unless the user overrides format()). Add a global enum decorator which changes the str() and repr() (and...
...structors There are four forms of constructors, applicable to both bytes and bytearray: bytes(<bytes>), bytes(<bytearray>), bytearray(<bytes>), bytearray(<bytearray>): simple copying constructors, with the note that bytes(<bytes>) might return its (immutable) argument, but bytearray(<bytearray>) always makes a copy. bytes(<str>, <encoding>[, <errors>]), bytearray(<str>, <encoding>[, <errors>]): encode a text string. Note t...
...str]], param: Optional[int]) -> Union[float, str] def f(list: List[int | str], param: int | None) -> float | str: pass f([1, "abc"], None) # Instead of typing.List[typing.Union[str, int]] typing.List[str | int] list[str | int] # Instead of typing.Dict[str, typing.Union[int, float]] typing.Dict[str, int | float] dict[str, int | float] The existing typing.Union and | syntax should be equivalent. int | str == typing.Union[int, str] typing.Union[int, int] == int int | int == int The...
...str owner: NotRequired[str|None] Okay (required for Python 3.5.3-3.6): class Dog(TypedDict): name: str owner: 'NotRequired[str|None]' No: class Dog(TypedDict): name: str # ick; avoid using both Optional and NotRequired owner: NotRequired[Optional[str]] Usage in Python <3.11 If your code supports Python <3.11 and wishes to use Required[] or NotRequired[] then it should use typing_extensions.TypedDict rather than typing.TypedDict because the latter will not unde...
...strings by calling str(path) which many found error-prone. One issue in converting path objects to strings comes from the fact that the only generic way to get a string representation of the path was to pass the object to str(). This can pose a problem when done blindly as nearly all Python objects have some string representation whether they are a path or not, e.g. str(None) will give a result that builtins.open() [5] will happily use to create a new file. Exacerbating this whole situation is t...
...str, bool]]) -> str: ... # Accepted def f(x: Z[int, str, bool]) -> str: ... # Equivalent # Both Z[[int, str, bool]] and Z[int, str, bool] express this: class Z_instantiated: f: Callable[[int, str, bool], int] Semantics The inference rules for the return type of a function invocation whose signature contains a ParamSpec variable are analogous to those around evaluating ones with TypeVars. def changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]: ... def retur...
...stract This PEP outlines the introduction of a raw bytes sequence type. Adding the bytes type is one step in the transition to Unicode-based str objects which will be introduced in Python 3.0. The PEP describes how the bytes type should work in Python 2.6, as well as how it should work in Python 3.0. (Occasionally there are differences because in Python 2.6, we have two string types, str and unicode, while in Python 3.0 we will only have one string type, whose name will be str but whose semanti...
...string keys, 'name' with value type str, and 'year' with value type int. The PEP 484 type Dict[str, Any] would be suitable, but it is too lenient, as arbitrary string keys can be used, and arbitrary values are valid. Similarly, Dict[str, Union[str, int]] is too general, as the value for key 'name' could be an int, and arbitrary string keys are allowed. Also, the type of a subscription expression such as d['name'] (assuming d to be a dictionary of this type) would be Union[str, int], which is ...
...str) -> bool f1: Callable[[int, str], bool] f2: (...) -> bool f2: Callable[..., bool] f3: async (str) -> str f3: Callable[[str], Awaitable[str]] f4: (**P) -> bool f4: Callable[P, bool] f5: (int, **P) -> bool f5: Callable[Concatenate[int, P], bool] f6: (*Ts) -> bool f6: Callable[[*Ts], bool] f7: (int, *Ts, str) -> bool f7: Callable[[int, *Ts, str], bool] Grammar and AST The proposed new syntax can be described by these AST changes to Parser/Python.asdl: expr = <p...
...str subclass, the return type is still str, not that subclass (see next example). For comparison, if the type variable was unconstrained, the common subclass would be chosen as the return type, e.g.: S = TypeVar('S') def longest(first: S, second: S) -> S: return first if len(first) >= len(second) else second class MyStr(str): ... result = longest(MyStr('a'), MyStr('abc')) The inferred type of result is MyStr (whereas in the AnyStr example it would be str). Also for comparison, i...
...str, int]] = {} shield: int = 100 captain: str def __init__(self, captain: str) -> None: ... assert get_type_hints(Starship) == {'hitpoints': int, 'stats': ClassVar[Dict[str, int]], 'shield': int, 'captain': str} assert get_type_hints(Starship.__init__) == {'captain': str, 'return': None} Note that if annotations are no...
From 28 Oct. through 30 Oct., 2016
Location: Leonardo Royal Hotel Munich, Moosacher Str. 90, 80809 München, Germany
PyCon DE 2016
...str and bytes. By default, a type variable ranges over all possible types. Example of constraining a type variable: from typing import TypeVar, Text AnyStr = TypeVar('AnyStr', Text, bytes) def concat(x: AnyStr, y: AnyStr) -> AnyStr: return x + y The function concat can be called with either two str arguments or two bytes arguments, but not with a mix of str and bytes arguments. There should be at least two constraints, if any; specifying a single constraint is disallowed. Subtypes of ...
...stract Rationale Motivation Proposed semantics for bytes and bytearray formatting %-interpolation Compatibility with Python 2 Proposed variations Objections Footnotes Copyright Abstract This PEP proposes adding % formatting operations similar to Python 2's str type to bytes and bytearray [1] [2]. Rationale While interpolation is usually thought of as a string operation, there are cases where interpolation on bytes or bytearrays make sense, and the work needed to make up for this missing f...
...str</font>): def g(x): return <font color="red">str</font>(x) return g System Message: WARNING/2 (<string>, line 68) Definition list ends without a blank line; unexpected unindent. </pre> In this example, the use of <font color="red">str</font> inside the inner function g() now refers to the argument <font color="red">str</font> in the outer function f(); previously (without nested scopes), it would refer to ...