tags:

views:

182

answers:

5

for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following

sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))]

this seems a touch ridiculous, surely there is a simpler way?

+1  A: 

You could do:

from os.path import dirname,realpath
sys.path.append(dirname(dirname(realpath(__file__))))

But to be honest, I prefer the full explicit version. It's much easier to read as a standalone statement.

Douglas Leeder
A: 

you can also do this

>>> from os.path import dirname as dn, realpath as rp

but its still better to explicitly define the name so you won't have variable names collision problems.

ghostdog74
A: 

Another option is to import path from os. It's not the most consise but I think it's still easy to read. Do you really want us to golf it? :)

from os import path
sys.path += [path.dirname(path.dirname(path.realpath(__file__)))]
gnibbler
A: 

If it is a huge problem, you could wrap os.path functionality is a path class. I'm pretty sure there is a Path module floating around on the internet.

mikerobi
+2  A: 

I've found Jason Orendorff's path module to be very nice. Unfortunately, it seems that his website is no longer on the internet, but you can still download the module from PyPI.

Zach Hirsch