New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
__match_args__ should work with pathlib.Path #108128
Comments
Why would having this feature be useful? In my own code I generally either convert to a known type (generally Also, how would adding some_path: Path = ...
match some_patch:
case Path(suffix=".png"):
... # process PNG files
case Path(suffix=".py"):
... # process Python source
case Path(suffix=suffix):
print(f"Unknown file extension {suffix!r}") |
The correct way to write that is this: from pathlib import Path
x = Path("/tmp/hello")
match x:
case Path() as path:
pass And that works today. You don't need to put It's only if you need to deconstruct this as a string that it would be useful, which I think there are occasionally use cases for. It's especially useful in the case I listed originally, where if case str(x) | os.PathLike(x):
... # x is a string But I'm afraid that would then require subclasses to also implement
Same way any other one works. For example (using Python 3.12 for Path subclassing): import pathlib
class Path(pathlib.Path):
__match_args__ = ("__match_self_prop__",)
@property
def __match_self_prop__(self) -> str:
return self.__fspath__() >>> f(Path("x.py"))
Got 'x.py'
>>> f(Path("x.txt"))
Didn't match |
Yeah, that would be a pretty significant feature request, which would require a PEP @henryiii :) It sounds pretty similar to the things @msullivan was proposing at the Python Language Summit this year: https://pyfound.blogspot.com/2023/05/the-python-language-summit-2023-pattern.html |
I didn't know I should use |
|
Is there anything to do here? I'm a bit of a newbie to |
@barneygale nah the take away is if you are trying to detect the type (what I was doing) to match on Foo() instead of Foo(_). This can be closed. |
Feature or enhancement
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
https://discuss.python.org/t/pattern-matching-and-paths/12819
Not exactly a huge discussion but at least illustrates that more than one person has run into this in practice :)
Proposal:
Ideally this should work:
It's not uncommon to write typed APIs that take
str | Path
and currently you can't use match to handle this. The discussion includes a snippet that would make it work if adopted, so I suspect this is an easy win.The text was updated successfully, but these errors were encountered: