A simpler more pythonic approach to adding in

R

rh0dium

Hi all,

I need a cleaner ( and shorter ) way to to look in my home directory or
any directory for a directory called modules. This is what I currently
have - but it is really ugly. Some a few of you experts point me to a
cleaner more pythonic approach?

mod = 0
if os.path.exists( os.environ['HOME'] + "/modules"):
sys.path.insert( 0, os.environ['HOME'] + "/modules")
mod =1
else:
path = os.environ['PWD']
while path != "/":
if os.path.exists( path + "/modules"):
sys.path.insert( 0, path + "/modules")
mod= 1
path = "/"
else:
path = os.path.split(path)[0]

if mod:
from foo import foo
 
G

George Sakkis

A cleaner, though not shorter, rewriting could be:

from itertools import chain

def ancestors(path):
while True:
yield path
parent = os.path.dirname(path)
if parent == path:
break
path = parent

for dir in chain([os.environ['HOME']],
ancestors(os.path.realpath('.'))):
modules_dir = os.path.join(dir, 'modules')
if os.path.exists(modules_dir):
sys.path.insert(0,modules_dir)
from foo import foo
break


HTH,
George
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top