After watching Raymond Hettingers talk Transforming Code into Beautiful, Idiomatic Python I got back to a function I wrote.

I'm not quite sure how to make it more pythonic but I think this might be a use-case to use the map function.

import logging
import string
import os

def _mounted_drives(possible_device_letters=string.ascii_uppercase):
    """Returns a set of mounted drive letters on a Windows machine."""
    result = set()
    for letter in possible_device_letters:
        mounted = os.path.exists(letter + ':')
        if mounted:
            logging.info('Found device ' + letter)

    return result

if __name__ == '__main__':
  • \$\begingroup\$ There shouldn't be a leading underscore in the function name. By convention, a leading underscore would indicate that it is a private member of a class. \$\endgroup\$ – 200_success Feb 17 '14 at 19:43

Removing the logging and using set comprehension :

def _mounted_drives(possible_device_letters=string.ascii_uppercase):
    return {l for l in possible_device_letters if os.path.exists(l + ':')}

If you do want the logging but you do not care about it being done once every device is found :

def _mounted_drives(possible_device_letters=string.ascii_uppercase):
    s = {l for l in possible_device_letters if os.path.exists(l + ':')}
    for l in s:
        logging.info('Found device ' + l)
    return s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.