yarl icon indicating copy to clipboard operation
yarl copied to clipboard

Provide `to_dict` method or make `URL` a mapping

Open dhirschfeld opened this issue 1 year ago • 2 comments

Is your feature request related to a problem?

It would be useful to be able to split a yarl.URL in a dictionary of it's constituent parts.

Describe the solution you'd like

I have a little helper function:

def to_dict(url: yarl.URL) -> dict:
    return dict(
        scheme=url.scheme,
        user=url.user,
        password=url.password,
        host=url.host,
        port=url.port,
        path=url.path,
        query=url.query,
        fragment=url.fragment,
    )
def test_to_dict(url: yarl.URL) -> None:
    assert yarl.URL.build(**to_dict(url)) == url

It would be convenient to either have this as a method or make the yarl.URL a mapping such that dict(url) would do the same thing as the to_dict function above.

Describe alternatives you've considered

Keep on defining my little helper whenever I use yarl :cry:

Additional context

No response

Code of Conduct

  • [X] I agree to follow the aio-libs Code of Conduct

dhirschfeld avatar Feb 02 '24 01:02 dhirschfeld

A mapping can be implemented by providing keys and __getitem__ methods - e.g.

class MappingURL(wrapt.ObjectProxy):

    def __init__(self, wrapped: yarl.URL):
        super().__init__(wrapped)

    def keys(self) -> list[str]:
        return [
            'scheme',
            'user',
            'password',
            'host',
            'port',
            'path',
            'query',
            'fragment',
        ]

    def __getitem__(self, key):
        return getattr(self, key)

image

dhirschfeld avatar Feb 02 '24 01:02 dhirschfeld

Hello, I see you jumped to the change you want in the project. Could you also explain your use case like I'm five? I'm struggling to understand why one would want to turn a well-defined type-checkable/lintable structure into a dict of arbitrary non-semantic keys and values... As things stand, I view this as a bad idea.

webknjaz avatar Feb 20 '24 14:02 webknjaz