Previous topic

Preprocessor in Python

Next topic

gromacs.utilities – Helper functions and classes

This Page

gromacs.fileformats.convert — converting entries of tables

The Autoconverter class was taken and slightly adapted from RecSQL, recsql.converter. It is mainly used by gromacs.fileformats.xpm.XPM to automagically generate useful NumPy arrays from xpm files. Custom conversions beyond the default ones in Autoconverter can be provided with the constructor keyword mapping.

class gromacs.fileformats.convert.Autoconverter(mode='fancy', mapping=None, active=True, sep=False, **kwargs)

Automatically convert an input value to a special python object.

The Autoconverter.convert() method turns the value into a special python value and casts strings to the “best” type (see besttype()).

The defaults for the conversion of a input field value to a special python value are:

value python
--- None
‘’ None
‘True’ True
‘x’ True
‘X’ True
‘yes’ True
‘Present’ True
‘False’ False
‘-‘ False
‘no’ False
‘None’ False
‘none’ False

If the sep keyword is set to a string instead of False then values are split into tuples. Probably the most convenient way to use this is to set sep = True (or None) because this splits on all white space whereas sep = ‘ ‘ would split multiple spaces.

Example
  • With sep = True: ‘foo bar 22 boing ---‘ –> (‘foo’, ‘boing’, 22, None)
  • With sep = ‘,’: 1,2,3,4 –> (1,2,3,4)

Initialize the converter.

Arguments :
mode

defines what the converter does

“simple”

convert entries with besttype()

“singlet”

convert entries with besttype() and apply mappings

“fancy”

first splits fields into lists, tries mappings, and does the stuff that “singlet” does

“unicode”

convert all entries with to_unicode()

mapping

any dict-like mapping that supports lookup. If``None`` then the hard-coded defaults are used

active or autoconvert

initial state of the Autoconverter.active toggle. False deactivates any conversion. [True]

sep

character to split on (produces lists); use True or None (!) to split on all white space.

encoding

encoding of the input data [utf-8]

convert(x)

Convert x (if in the active state)

active

If set to True then conversion takes place; False just returns besttype() applid to the value.

active

Toggle the state of the Autoconverter. True uses the mode, False does nothing

gromacs.fileformats.convert.besttype(x, encoding='utf-8')

Convert string x to the most useful type, i.e. int, float or unicode string.

If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned.

Note

Strings will be returned as Unicode strings (using unicode()), based on the encoding argument, which is “utf-8” by default.

gromacs.fileformats.convert.to_unicode(obj, encoding='utf-8')

Convert obj to unicode (if it can be be converted)

from http://farmdev.com/talks/unicode/