allpy
changeset 778:9e0e0fb4908c
replace pdb_getter functions with functors
download_pdb and cached_download_pdb are now instances
of functor classes.
Arguments can be passed into construstor of functor:
my_pdb_getter = CachedDownloadPdb(cache_dir='/tmp')
sequence.auto_pdb(pdb_getter=my_pdb_getter)
author | boris (kodomo) <bnagaev@gmail.com> |
---|---|
date | Tue, 12 Jul 2011 22:25:52 +0400 |
parents | 0d1ba84a4080 |
children | 6d6285392ae4 |
files | allpy/structure.py |
diffstat | 1 files changed, 29 insertions(+), 19 deletions(-) [+] |
line diff
1.1 --- a/allpy/structure.py Tue Jul 12 21:14:58 2011 +0400 1.2 +++ b/allpy/structure.py Tue Jul 12 22:25:52 2011 +0400 1.3 @@ -48,27 +48,37 @@ 1.4 def get_structure(file, name): 1.5 return PDBParser().get_structure(name, file) 1.6 1.7 -def download_pdb(code, pdb_url=config.pdb_url): 1.8 - """ Download pdb_file from web and return unnamed tempfile """ 1.9 - url = pdb_url % code 1.10 - print "Download %s" % url 1.11 - return urllib2.urlopen(url) 1.12 +class DownloadPdb(object): 1.13 + """ Functor downloading pdb from web """ 1.14 + def __init__(self, pdb_url=config.pdb_url): 1.15 + """ pdb_url -- format string, template of url """ 1.16 + self.pdb_url = pdb_url 1.17 + def __call__(self, code): 1.18 + url = self.pdb_url % code 1.19 + print "Download %s" % url 1.20 + return urllib2.urlopen(url) 1.21 +download_pdb = DownloadPdb() 1.22 1.23 -def cached_download_pdb(code, pdb_url=config.pdb_url, cache_dir='pdb_cache'): 1.24 - path = os.path.join(cache_dir, code + '.pdb') 1.25 - if os.path.exists(path): 1.26 +class CachedDownloadPdb(object): 1.27 + def __init__(self, pdb_url=config.pdb_url, cache_dir='pdb_cache'): 1.28 + self.pdb_url = pdb_url 1.29 + self.cache_dir=cache_dir 1.30 + def __call__(code): 1.31 + path = os.path.join(self.cache_dir, code + '.pdb') 1.32 + if os.path.exists(path): 1.33 + return open(path) 1.34 + if not os.path.exists(self.cache_dir): 1.35 + os.mkdir(self.cache_dir) 1.36 + try: 1.37 + with open(path, 'w') as out_file: 1.38 + in_file = download_pdb(code, pdb_url=self.pdb_url) 1.39 + out_file.write(in_file.read()) 1.40 + in_file.close() 1.41 + except BaseException: 1.42 + os.unlink(path) 1.43 + raise 1.44 return open(path) 1.45 - if not os.path.exists(cache_dir): 1.46 - os.mkdir(cache_dir) 1.47 - try: 1.48 - with open(path, 'w') as out_file: 1.49 - in_file = download_pdb(code, pdb_url=pdb_url) 1.50 - out_file.write(in_file.read()) 1.51 - in_file.close() 1.52 - except BaseException: 1.53 - os.unlink(path) 1.54 - raise 1.55 - return open(path) 1.56 +cached_download_pdb = CachedDownloadPdb() 1.57 1.58 class SequenceMixin(base.Sequence): 1.59 """Mixin for adding PDB data to a Sequence.