1
\$\begingroup\$

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?

asked Jul 9, 2013 at 9:02
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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:
 ...
answered Jul 9, 2013 at 9:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.