Skip to content

support of type hints #886

Closed
Closed

Description

@timrid

Is there any way to use type hints of the typing module for a construct.Struct? Then the auto completion of the IDE could be used (in my case VSCode with the pylance extension).

Activity

  1. arekbulski commented on Nov 29, 2020

    @arekbulski
    Member

    Short answer is no, full answer is maybe. I explicitly declined to use type annotations in Construct. But if I remember correctly, someone wrote an adapter for those, just search the issues for it.

  2. arekbulski commented on Nov 29, 2020

    @arekbulski
    Member

    Found it: #814

  3. timrid commented on Nov 29, 2020

    @timrid
    Author

    Thank you for the answer and the search of the issue. I thought I had already searched all issues on the topic. Apparently not ;)

    The example from joernheissler is a nice approach, but unfortunately not completely usable with VSCode in combination with pylance without producing error messages.

    So I try to build a wrapper for your very good package Construct myself. If I have something that works, I would post it here to get feedback, if that is ok.

  4. timrid commented on Dec 2, 2020

    @timrid
    Author

    Here is my first Version of a Wrapper: Link

    It works completely without meta classes compared to #814.

    This example is only executable from Python 3.9 on, because "typing.Annotated" is used. Maybe i can make it backwards compatible by using the "typing-extensions" package.

    It became quite a lot of code, because I wrote a wrapper class for each construct. Maybe we can save these wrappers if we integrate the type hints directly into the package.

    The code runs without error messages in VSCode with the pylance extension and Python 3.9. For each parsed object an autocomplete is available. And if you hover over the code, the types are displayed correctly.

    hA3AXLzCmj

    What do you think about this approach?

  5. arekbulski commented on Dec 2, 2020

    @arekbulski
    Member

    What is the code for Entry?

  6. timrid commented on Dec 2, 2020

    @timrid
    Author

    Hhere is an snippet from my posted example:

    ParsedTypeHint = TypeVar("ParsedTypeHint")
    BuildTypesHint = TypeVar("BuildTypesHint")
    
    
    ...
    
    
    class Struct(TypedConstruct[ParsedTypeHint, ParsedTypeHint]):
        _construct: cs.Struct
    
        def __init__(self, struct_type: Type[ParsedTypeHint]):
            struct_entries = []
    
            # extract the construct formats from the struct_type
            entry_hints = typing.get_type_hints(struct_type, include_extras=True)
            for entry_name, entry_hint in entry_hints.items():
                args = typing.get_args(entry_hint)
                if len(args) != 2:
                    raise ValueError("wrong annotation")
                entry_format = args[1]
                if not isinstance(entry_format, TypedConstruct):
                    raise ValueError("wrong annotation")
                struct_entries.append(entry_name / entry_format._construct)
    
            self._construct = cs.Struct(*struct_entries)
            self._parsed_type = struct_type
    
    
    ...
    
    
    def Entry(obj: TypedConstruct[ParsedTypeHint, BuildTypesHint]) -> Type[ParsedTypeHint]:
        return Annotated[ParsedTypeHint, obj]

    Most of the magic takes place in Entry and Struct. With Entry a typing.Annotated is created, which binds the type of the entry together with the TypedConstruct format of the entry.
    In Struct the individual entries of the container are extracted to create a standard Construct Struct.

  7. arekbulski commented on Dec 3, 2020

    @arekbulski
    Member

    I never used type annotations myself, so I dunno. To me its a bit overcomplicating things. For writing python I never used anything more complex than a notepad. But I am happy that it works for you. Please post whatever else you invented so that other people can benefit.

  8. timrid commented on Dec 3, 2020

    @timrid
    Author

    For smaller projects a notepad may be sufficient, but as soon as you want to set up a slightly larger project, auto-complete is very useful.

    I have worked on my approach a bit further. What is very complicated in my old example is that a separate wrapper class must be written for each construct.

    The approach I'm currently working on (and it works quite well at the moment) is to create a stub file (.pyi) for each file of this package. Then the whole package could stay as it is, only that a new Struct class (e.g. TypedStruct) would be added, following the approach shown above. My current stubs looks this: Stubs Example

    Would this be a possibility for you to include in this package? The existing code would not have to be modified (except for including the new TypedStruct class) and several .pyi files would be added.

  9. arekbulski commented on Dec 4, 2020

    @arekbulski
    Member

    Well... I am not keen on adding type annotations to Construct in any way, shape or form. You can post it here, or host it in your own repository and I will add a link to it in the main documentation. Good enough?

  10. timrid commented on Dec 4, 2020

    @timrid
    Author

    Okay, too bad. But understandable. Then I will do it in a separate repository. A nice offer to link it in the documentation.
    As soon as I have a presentable version, I will get back to you here.

  11. arekbulski commented on Dec 5, 2020

    @arekbulski
    Member

    PLEASE KEEP THIS THREAD OPEN.

  12. timrid commented on Jan 3, 2021

    @timrid
    Author

    After many days of work on it over the holidays, I have now finished the stubs for the complete construct package. In addition, I have created a new package construct_typed with adapter constructs, which allow an improved static code analysis. But this adapters are currently in an experimental state.

    I tested the stubs using the existing pytest from this repo, which had to be slightly modified in some cases. I have added these modifed tests to the new repo. They run with mypy without errors. And pyright create only a few errors, which i can hopefully fix in the future.

    https://github.com/timrid/construct-typing
    https://pypi.org/project/construct-typing/

    What do you think of the implementation?

  13. arekbulski commented on Jan 3, 2021

    @arekbulski
    Member

    Well, I have to admit that this thing that you are proposing is beyond my understanding of Python. But I do like it and support it. Good job. I think many people will like it and benefit from it. Its even possible that your package might supercede my package at some point and you will carry it onward and upward. Who knows, right?

  14. timrid commented on Jan 3, 2021

    @timrid
    Author

    Currently I do not plan to replace your package. Some of the functions are still a bit magic for me, like the compile function. I see it currently only as an extension. But who knows what the future will bring.

    At first I would like others to test this extension to get an opinion about the usability to get away from the experimental status. Maybe others have even better/simpler ideas on how to implement it. And also I will first use it in different projects to gain experience. If I have some more time, I will try to implement some examples from your gallery.

    Side Note:
    During my development of the stubs I also noticed that currently the typing module and the static type checker get new functions almost monthly. To name a few examples:

    • Higher-Kinded TypeVars python/typing#548 Higher-Kinded TypeVars
    • Variadic generics
    • PEP 593: Flexible function and variable annotations with the Annotated keyword in python 3.9 (which I intentionally left out to remain compatible with older python versions)
    • PEP 585: Type Hinting Generics In Standard Collections in python 3.10
    • PEP 612: Parameter Specification Variables in python 3.10
    • PEP 604: New Type Union Operator in python 3.10
    • PEP 563: Postponed Evaluation of Annotations Becomes Default in python 3.10

    Maybe it is possible to get even better / simpler type hints with these python extensions. But python 3.9 is still relatively new (from October 2020) and python 3.10 is not yet officially released, so I think that we should wait some time before they are used productively.

  15. arekbulski commented on Jan 3, 2021

    @arekbulski
    Member

    Compilation is meant to generate a string which looks like a python module handwritten to parse whatever that you want to parse. Have you read the documentation for it? Here it is:
    https://construct.readthedocs.io/en/latest/compilation.html

  16. arekbulski commented on Jan 27, 2021

    @arekbulski
    Member

    I finally read through your repository and I am shocked and dismayed how much you added to the package. When I read Mypy documentation my impression was that adding type checking makes a beautiful pure Python code into C++ alike nasty shit. After reading your package code, I am sure of it. Dont get me wrong. I applaud you for your contribution. I just dont like type checking in general. I think its clutter and it makes things harder for me, not easier. Thankfully, GitHub does not curate repositories and instead it gives everyone an opportunity to publish whatever code they want to develop. I remain skeptical of typing but I will also keep supporting your efforts as much as I am able.

    Btw, in construct-typing your requirements.txt has unpinned construct version but setup.py has a pinned version. Is this how it is supposed to be?

    I am finishing merging all the fixes that people PRed over last year. I will publish new version today or tomorrow. Maybe you wanna update on your side or something? Just giving you heads up.

  17. timrid commented on Jan 27, 2021

    @timrid
    Author

    Yes, it is true that the type annotations do not make the Python code more readable. But what makes up for this disadvantage for me is the advantage of static analysis of the code before it is executed. E.g. if you rename a variable that you use in 10 other places in your code over several files, you can see directly where it doesn't fit and don't have to re-run the code every time the error occurs at runtime (especially if you don't have unit tests, many errors remain hidden for a long time...).

    The nice thing about my chosen approach with the stub files is that they don't affect your code at runtime one bit. So if there should be an error in the stub files, at most an error message is displayed in the IDE, but the code would still run without problems.

    But I don't think I can convince you any further. It is and remains a matter of taste ;)

    Nice to hear that you found time to look at the PRs. I will have a look at your changes as soon as I find time and merge them into the stubs. I will also fix the unintended difference between requirements.txt and setup.py.

    If you are already creating a new version, what about this offer?

    Well... I am not keen on adding type annotations to Construct in any way, shape or form. You can post it here, or host it in your own repository and I will add a link to it in the main documentation. Good enough?

  18. arekbulski commented on Jan 27, 2021

    @arekbulski
    Member

    I would not call it a matter of taste, rather its a trade-off. Static analysis gives you intellisense autocompletion. Well, I use Sublime editor and I have a basic autocompletion too. And no intellisense rename but I do have Find and Replace. My point is that the advantage you are talking about seems to be useless to me. Ah and I forgot about the biggest one: I have a comprehensive test suite. If I had to choose between typing and testing, I would pick a test suite for sure.

    You mean offer to add type hints? Well, there are two issues with that. For one, I dont want to add something that I am not comprehending myself. Which leads to second which is, I would need to make you a maintainer. But I am hesitant to relinquish control over the repository. Right now, what I say goes and I like to keep it that way.

    I could use your help tho, if you want to contribute to something important. Its issue #894 which is pickling classes. It didnt work years ago and it doesnt work now and I have no clue how to fix it. If you want to contribute, here is the most important task.

  19. timrid commented on Jan 30, 2021

    @timrid
    Author

    Oh no, I don't mean adding the typing. I meant the offer to put a link to my repository in the main documentation, so that my extension can be found by others who like type annotations.

    Unfortunately I'm not really into pickling either...

  20. arekbulski commented on Jan 30, 2021

    @arekbulski
    Member

    I was thinking where to put a link and I am unsure. Look at the main docs and tell me, where would you like me to link it? Maybe just a one line with a link in transision page, or maybe a whole page like compilation page? In second case you would need to write an entire page about your package. Which might be worthwhile.

  21. timrid commented on Feb 2, 2021

    @timrid
    Author

    Unfortunately, I don't have the time to create an entire page with a detailed description. How about a new short subsection under "Introduction" like this:

    Type Hints / Type Annotations
    As an extension to this library there is the construct-typing library, which provides PEP 561 compliant stub files for this library. It also provides extended adapters to describe complex structures using PEP 526 type annotations for improved static code analysis with e.g. mypy.

    pip install construct-typing

  22. arekbulski commented on Feb 2, 2021

    @arekbulski
    Member

    Could you PR it? Otherwise its fine, I will paste it myself.
    Nevermind. I will handle it tomorrow.

  23. arekbulski commented on Feb 3, 2021

    @arekbulski
    Member
  24. timrid commented on Feb 4, 2021

    @timrid
    Author

    Perfect, thanks. I think I can close this issue now.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions