0

From How to get the home directory in Python? and How to find the real user home directory using python?, it's possible to find the user's home directory with:

import os
os.path.expanduser('~/')

But would there be a chance that os.path.expanduser() can't find anything and returns ~/?

I'm asking this question because, from nltk, there's this line at https://github.com/nltk/nltk/blob/develop/nltk/downloader.py#L951

homedir = os.path.expanduser('~/')
if homedir == '~/':
    raise ValueError("Could not find a default download directory")

Note: The question is not asking how to find the user home directory, it's asking whether there's any point in checking for the value of the os.path.expanduser and raising an Error.

Community
  • 1
  • 1
alvas
  • 115,346
  • 109
  • 446
  • 738
  • Possible duplicate of [How to find the real user home directory using python?](http://stackoverflow.com/questions/2668909/how-to-find-the-real-user-home-directory-using-python) – Zain I. May 09 '17 at 04:15
  • Yes, and a `ValueError` is a good thing to `raise` since the code should not proceed further at this point, until such point as there is another strategy used for finding the correct directory. – JacobIRR May 09 '17 at 04:30

1 Answers1

1

In the official document.

On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.

...

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

So as the document saying, if the operation fails, it will return the original string. And, the point is, return unchanged path but not constantly ~/.

Sraw
  • 18,892
  • 11
  • 54
  • 87