Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to abstract away differences between zipfile and rarfile modules. In my code i want to call ZipFile or RarFile constructors depending on file format. Currently i do it like that.

def extract(dir, f, archive_type):
    '''
    archive_type should be 'rar' or 'zip'
    '''
    images = []

    if archive_type == 'zip':
        constructor = zipfile.ZipFile
    else:
        constructor = rarfile.RarFile

    with directory(dir):
        with constructor(encode(f)) as archive:
            archive.extractall()
        os.remove(f)
        images = glob_recursive('*')

    return images

Is there any more elegant way for dynamic object calling?

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Classes are first-class objects in Python.

amap = {
  'zip': zipfile.ZipFile,
  'rar': rarfile.RarFile
}

 ...

with amap[archive_type](encode(f)) as archive:
   ...

or

with amap.get(archive_type, rarfile.RarFile)(encode(f)) as archive:
   ...
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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