开发者

Pythonize if/else

开发者 https://www.devze.com 2023-03-23 16:42 出处:网络
My mind is probably feeling Friday afternoon and I cannot see a way to pytonize the code below: filepath = None

My mind is probably feeling Friday afternoon and I cannot see a way to pytonize the code below:

filepath = None
if 'HALLO' in os.environ:
    filepath = os.environ['HALLO']
elif os.path.isfile( os.path.join(os.environ['HOME'], 'host.hallo') ):
    filepath = os.path.join(os.environ['HOME'], 'host.hallo')
elif os.path.isfile('/etc/app/host.hallo'):
    filepath = '/etc/app/host.hallo'
if filepath:
    print '开发者_JS百科HALLO found in "%s"' % filepath
    ## do something
else:
    print 'HALLO not found!'
    ## do something else

Any idea on how to do it? Thanks!

ps: the code above is just an example, it can have a syntax error since I have written it directly here.


This should work pretty well:

paths = [
    os.environ.get('HALLO', None),
    os.path.join(os.environ['HOME'], 'host.hallo'),
    '/etc/app/host.hallo',
]

for path in paths:
    if path and os.path.isfile(path):
        break
else:
    # Handle no path
    pass

# Use path here

Additionally, it allows you to add more paths to check easily.


You're looking for the first nonzero filepath? use any(). You can also factor out the os.path.isfile using a list comprehension/generator expression.

filepath = any(filename 
               for filename 
               in (os.environ.get('HALLO'), 
                   os.path.join(os.environ['HOME'], 'host.hallo'),
                   '/etc/app/host.hallo')
               if os.path.isfile(filename))

if filepath:
    print 'HALLO found in "%s"' % filepath
    ## do something
else:
    print 'HALLO not found!'
    ## do something else


home_hallo = os.path.join(os.environ['HOME'], 'host.hallo')
filepath = ( ('HALLO' in os.environ and os.environ['HALLO']) or
             (os.path.isfile(home_hallo) and home_hallo) or
             (os.path.isfile('/etc/app/host.hallo') and '/etc/app/host.hallo') )
if filepath:
    print 'HALLO found in "%s"' % filepath
    ## do something
else:
    print 'HALLO not found!'
    ## do something else

See the documentation on Boolean operations if it isn't clear why this works, here is the summary:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消