Skip to content

Support type aliases in formats 'list[int]' and 'int | float' in argument conversion #4711

Closed

Description

@pekkaklarck

Our argument conversion typically uses actual types like int, list[int] and int | float, but we also support type aliases as strings like 'int' or 'integer'. The motivation for type aliases is to support types returned, for example, by dynamic libraries wrapping code using other languages. Such libraries can simply return type names as strings instead of mapping them to actual Python types.

There are two limitations with type aliases, though:

  • It isn't possible to represent types with nested types like 'list[int]'. Aliases always map to a single concrete type, not to nested types.
  • Unions cannot be represented using "Python syntax" like 'int | float'. It is possible to use a tuple like ('int', 'float'), though, so this is mainly an inconvenience.

Implementing this enhancement requires two things:

  • Support for parsing strings like 'list[int]' and 'int | float'. Results could be newish TypeInfo objects that were added to make Libdoc handle nested types properly (Libdoc doesn't handle parameterized types like list[int] properly #4538). Probably we could add a new TypeInfo.from_string class method.
  • Enhance type conversion to work with TypeInfo. Currently these objects are only used by Libdoc.

In addition to helping with libraries wrapping non-Python code, this enhancement would allow us to create argument converters based on Libdoc spec files. That would probably be useful for external tools such as editor plugins.

Activity

  1. added this to the milestone on Mar 30, 2023
  2. pekkaklarck commented on Mar 30, 2023

    @pekkaklarck
    MemberAuthor

    This enhancement would also help with normal Python libraries when using Python versions that do not support the modern list[int] (requires Python 3.9) and int | float (requires Python 3.10) syntax. Type checkers support stringifying types like

    def example(a: 'list[int]', b: 'int | float'):
        ...

    but the type hints we get are also strings. If this enhancement is implemented, we'd support type hints like above with all Python versions in our argument conversion.

  3. pekkaklarck commented on Mar 30, 2023

    @pekkaklarck
    MemberAuthor

    Parsing strings like 'list[int]' and 'int | float' isn't exactly trivial, because we also need to support nested usages like 'list[ list[int] | tuple[ float | int | dict[str, int|float]]]'. I created a parser that can do that as an experiment and include it below. It would need some cleanup still and, more importantly, proper unit test. It also would need to be integrated with the existing TypeInfo class.

    from enum import Enum, auto
    from dataclasses import dataclass
    
    
    class TokenType(Enum):
        NAME = auto()
        LEFT_SQUARE = auto()
        RIGHT_SQUARE = auto()
        PIPE = auto()
        COMMA = auto()
    
        def __repr__(self):
            return str(self)
    
    
    @dataclass
    class Token:
        type: TokenType
        value: str
        position: int = -1
    
    
    class Scanner:
        markers = {
            '[': TokenType.LEFT_SQUARE,
            ']': TokenType.RIGHT_SQUARE,
            '|': TokenType.PIPE,
            ',': TokenType.COMMA,
        }
    
        def __init__(self, source: str):
            self.source = source
            self.tokens: 'list[Token]' = []
            self.start = 0
            self.current = 0
    
        @property
        def at_end(self):
            return self.current >= len(self.source)
    
        def scan(self):
            while not self.at_end:
                self.start = self.current
                char = self.advance()
                if char in self.markers:
                    self.add_token(self.markers[char])
                elif char.strip():
                    self.name()
            return self.tokens
    
        def advance(self):
            char = self.source[self.current]
            self.current += 1
            return char
    
        def peek(self):
            try:
                return self.source[self.current]
            except IndexError:
                return None
    
        def name(self):
            end_at = set(self.markers) | {None}
            while self.peek() not in end_at:
                self.advance()
            self.add_token(TokenType.NAME)
    
        def add_token(self, type: TokenType):
            value = self.source[self.start:self.current].strip()
            self.tokens.append(Token(type, value, self.start))
    
    
    class Parser:
    
        def __init__(self, source: str):
            self.source = source
            self.tokens: 'list[Token]' = []
            self.current = 0
    
        @property
        def at_end(self) -> bool:
            return self.peek() is None
    
        def parse(self) -> 'TypeInfo':
            self.tokens = Scanner(self.source).scan()
            info = self.type()
            if not self.at_end:
                self.error('Tokens remaining.')
            return info
    
        def type(self) -> 'TypeInfo':
            if not self.check(TokenType.NAME):
                self.error('Token name missing.')
            info = TypeInfo(self.advance().value)
            if self.match(TokenType.LEFT_SQUARE):
                info.nested = self.nested()
            if self.check(TokenType.PIPE):
                info = TypeInfo('Union', nested=[info])
                while self.match(TokenType.PIPE):
                    info.nested.append(self.type())
            return info
    
        def nested(self) -> 'list[TypeInfo]':
            types = []
            while not types or self.match(TokenType.COMMA):
                types.append(self.type())
            if not self.check(TokenType.RIGHT_SQUARE):
                self.error("']' missing.")
            self.advance()
            return types
    
        def match(self, *types: TokenType) -> bool:
            for typ in types:
                if self.check(typ):
                    self.advance()
                    return True
            return False
    
        def check(self, expected: TokenType) -> bool:
            peeked = self.peek()
            return peeked and peeked.type == expected
    
        def advance(self) -> Token:
            token = self.peek()
            if token:
                self.current += 1
            return token
    
        def peek(self) -> 'Token | None':
            try:
                return self.tokens[self.current]
            except IndexError:
                return None
    
        def error(self, message: str):
            token = self.peek()
            position = f'in index {token.position}' if token else 'at end'
            raise ValueError(f"Parsing type info {self.source!r} failed: "
                             f"Error {position}: {message}")
    
    
    class TypeInfo:
    
        def __init__(self, name: str, nested: 'list[TypeInfo] | None' = None):
            self.name = name
            self.nested = nested or []
    
        def __str__(self):
            if not self.nested:
                return self.name
            if self.name == 'Union':
                return ' | '.join(str(n) for n in self.nested)
            nested = ', '.join(str(n) for n in self.nested)
            return f'{self.name}[{nested}]'
    
    
    # testing...
    
    def test_valid():
        for valid in ['int', 'int | float', 'list[int]', 'dict[str, int]', 'tuple[int|str]',
                      'list[ list[int] | tuple[ float | int | dict[str, int|float]]]']:
            print(f'Original: {valid}')
            tokens = Scanner(valid).scan()
            print(f'Tokens:\n{tokens}')
            info = Parser(valid).parse()
            print(f'Parsed: {info}')
            print()
    
    
    def test_invalid():
        for invalid in ['', '|', 'int|', 'list[int', 'list[int, float,]']:
            try:
                Parser(invalid).parse()
            except ValueError as err:
                print(err)
    
    
    test_valid()
    test_invalid()
  4. modified the milestones: , v7.0 on Jun 2, 2023
  5. self-assigned this
    on Sep 14, 2023
  6. pekkaklarck commented on Sep 22, 2023

    @pekkaklarck
    MemberAuthor

    Basic functionality is now done and the feature is also documented. This is what we still need to do:

    • Error reporting when using broken type hint like 'list[int'.
    • Unit test for TypeInfoParser and possibly also for TypeInfoTokenizer, including error situations.
    • Refactor. For example, move all type inspection, handling aliases, etc. from type converters to TypeInfo.
  7. pekkaklarck commented on Sep 28, 2023

    @pekkaklarck
    MemberAuthor

    Error reporting has been improved and using something like list[int now causes an error taking the keyword into use. In practice characters [, ], , and | that have a special meaning with types cause problems (unless used as intended). Using non-type strings is otherwise still supported. For example, arg: Hello, world! will now cause an error due to the comma, but arg: Hello world! is still ok. In the future, possibly still as part of this issue, we may want to restrict type names to alpha numeric characters. Regardless is that done, already this change makes this issue backwards incompatible.

  8. pekkaklarck commented on Oct 3, 2023

    @pekkaklarck
    MemberAuthor

    After some more refactoring and enhancements this issue ought to now be done.

  9. pekkaklarck commented on Nov 13, 2023

    @pekkaklarck
    MemberAuthor

    Changes to TypeConverter done as part of this issue turned out to cause backwards incompatibility issues (#4942). TypeConverter wasn't officially part of the public API so we most likely won't revert the changes, but instead add a new public API for that purpose. Anyway, also this is a backwards incompatible change that should be mentioned in the release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions