-1

I have the following line of code which I think is not correct:

path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))

where os.path.dirname(__file__) looks for a script.

I understand that os.path.abspath() gives you the absolute path of a file or a directory but os.path.join() combines two strings together but for that we need to have 2 paths. i.e. path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

Am I correct in thinking that the above code is incorrect and broken?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jay
  • 33
  • 1
  • 4

2 Answers2

3

The os.path.join() call is entirely redundant, and can be safely removed. You don't need it here. It is not technically wrong or broken however.

os.path.join() accepts an arbitrary number of arguments (at least 1) to join together, so while it is technically permitted to pass in just the result of os.path.dirname(__file__), os.path.join() can only return that single input.

It is probably an artefact of a code refactor or half-understood copy-and-paste action where more arguments have been removed since.

os.path.join() accepts a single argument for the case where you use *args syntax to pass in additional paths, but those extra paths are empty based on runtime conditions:

base = '....'
additional = ()
if some_condition:
    additional = ('additional', 'elements')
path = os.path.join(base, *additional)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

os.path.join(path, *paths) Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

Python 2.7 documentation

Jeff Hemmen
  • 181
  • 12