Search code examples
pythonpathlib

How to use `case_sensitive` option in pathlib glob?


In the documentation of pathlib, it says

Path.glob(pattern, *, case_sensitive=None)

There is two things I do not understand.

  1. what is the second parameter * ?

  2. I want to use case_sensitive option. But when I run

    somepath.glob('*.txt',case_sensitive=False)

I got TypeError: glob() got an unexpected keyword argument 'case_sensitive'

How to use case_sensitive option in pathlib glob?


Solution

  • A lone * without a parameter name indicates that everything following is a keyword-only argument. That is, with the declaration

    def glob(pattern, *, case_sensitive=None)
    

    We can pass pattern positionally or by-name, but we can only pass case_sensitive by name. So all of the following are valid

    path.glob('*')
    path.glob(pattern='*')
    path.glob('*', case_sensitive=True)
    path.glob(pattern='*', case_sensitive=True)
    path.glob(case_sensitive=True, pattern='*')
    

    But this is not

    path.glob('*', True)
    

    The Python designers wrote the function in this way to force you to write more readable code. If you were able to write path.glob('*', True), then everyone reading your code (including you in two weeks) would have to go look up what that second parameter is. But with the case_sensitive=True syntax, it's immediately self-evident.

    As for your second question, the documentation specifies

    Changed in version 3.12: The case_sensitive parameter was added.

    So I suspect you're running a version of Python older than 3.12.