Skip to content

Using types-lxml types in external code #14

Closed

Description

@roblframpton

This library does a great job of typing the results from lxml functions. I can see, for example, that the XML parse method returns a type _ElementTree[_Element]. However, I cannot see a way to use these types in my own code. For example, I'd like to write a method which takes an ElementTree as an argument:

def my_func(element: _ElementTree[_Element]):
  pass

but I can't work out how to import these types. I tried:

from types_lxml import _ElementTree, _Element

but this didn't work. So:

  1. Is there a way to import these types to use in our own code?
  2. Could this be documented somewhere in the readme?

Thanks!

Activity

  1. abelcheung commented on Apr 11, 2023

    @abelcheung
    Owner

    Is there a way to import these types to use in our own code?

    First things first, actually it is expected to only import classes from source, not from external stubs directly.

    And there are a few ways to migitate the problem:

    1. Quote the type with double quotes so python interpreter would treat annotation as strings
      from lxml.etree import _ElementTree, _Element
      def my_func(element: "_ElementTree[_Element]"):
        pass
    2. Use __future__:
      from __future__ import annotations
      from lxml.etree import _ElementTree, _Element
      def my_func(element: _ElementTree[_Element]):
        pass

    (2) automatically helps achieving (1) for you without your intervention, but you would need to remember adding __future__ to the very top of every file where it is used.

    Could this be documented somewhere in the readme?

    Yes, the documentation absolutely needs some love. I think I can get something done after clearing my current tasks at hand. I'll leave the report open for now as reminder.

  2. added
    question
    on Apr 11, 2023
  3. roblframpton commented on Apr 11, 2023

    @roblframpton
    Author

    Thanks a lot for your response, that has solved things for me.

  4. abelcheung commented on Apr 17, 2023

    @abelcheung
    Owner

    Doc now available on wiki.

  5. Repository owner locked and limited conversation to collaborators on Apr 17, 2023
  6. converted this issue into a discussion #18 on Apr 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions