Source code for epygram.formats_factory

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Utilities to play with resource formats:

- guess the format of an existing resource in a given container,
- create a Resource instance with a generic function,
  eventually (if already existing) without knowing its format *a priori*.
- ... 
"""

from footprints import proxy as fpx

from epygram import config, epygramError



[docs]def guess(filename): """ Returns the name of the format of the resource located at a given **filename**, if succeeded. """ for f in config.implemented_formats: # and not the list of dataformat from footprints collectors, because the order is important. try: r = fpx.dataformat(filename=filename, openmode='r', format=f) r.close() fmt = f break except Exception: fmt = 'unknown' return fmt
[docs]def resource(filename, openmode, fmt=None, **kwargs): """ Returns an instance of Resource of the requested *fmt* format, located at the given *filename* (:class:`epygram.base.File`, ...), and with the given *openmode*. If *fmt* is not given, tries to guess it (only for *openmode* 'r' or 'a'). Other *kwargs* are passed to the resource constructor. """ if fmt == None and openmode in ('r', 'a'): fmt = guess(filename) if fmt == 'unknown': raise epygramError("unable to guess format of resource at: "+filename) elif fmt == None and openmode == 'w': raise epygramError("must specify 'fmt' argument with 'openmode' == 'w'.") return fpx.dataformat(filename=filename, openmode=openmode, format=fmt, **kwargs)