Search code examples
python-3.xpathlib

Exists something like a Nonetype path?


In my classes I like to initiate my path variables with None. If I use os.path it is easy to compare with other paths. But I like more the pathlib style.

Is there a solution to do this:

import os

path1 = os.path.dirname('D\\test\\file.py')
path2 = None

if path1 == path2:
    print('OK')

With pathlib?

My Attempt was this:

from pathlib import Path

test1 = Path('D/test/file.py')
test2 = Path(None)

if test1.resolve() == test2.resolve():
    print('ok')

But this is not working because Path() doesn't accept None and None hast no method resolve()


Solution

  • You could give yourself a sentinel whose resolve method returns None to do your checks.

    Example:

    from pathlib import Path
    
    # You can use type to quickly create a throwaway class with a resolve method
    NonePath = type('NonePath', (), {'resolve': lambda: None})
    
    test1 = Path('D/test/file.py')
    test2 = NonePath
    
    if test1.resolve() == test2.resolve():
        print('ok')
    elif test2.resolve() is None: # returning None allows you to do your check
        print('test2 is NonePath')
    
    

    You could go even farther with that and pull the __dict__ from Path and exchange all the methods and attributes with None but that seems like overkill.

    Disclaimer: This is probably a bad idea

    from pathlib import Path
    # this changes all methods to return None
    # and sets all attributes to None
    # if they aren't dunder methods or attributes
    path_dict = {k: lambda: None if callable(v) else None 
                 for k, v in Path.__dict__.items() 
                 if not k.startswith('__')}
    
    NonePath = type('NonePath', (), path_dict)