How to use the f90nml.namelist.Namelist function in f90nml

To help you get started, we’ve selected a few f90nml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github marshallward / f90nml / tests / test_f90nml.py View on Github external
def test_groups(self):
        d = {'a': {'b': 1.}}
        nml = Namelist(d)
        key, value = next(nml.groups())
        self.assertEqual(key, ('a', 'b'))
        self.assertEqual(value, 1.)
github marshallward / f90nml / tests / test_f90nml.py View on Github external
def test_f90repr(self):
        nml = Namelist()
        self.assertEqual(nml._f90repr(1), '1')
        self.assertEqual(nml._f90repr(1.), '1.0')
        self.assertEqual(nml._f90repr(1+2j), '(1.0, 2.0)')
        self.assertEqual(nml._f90repr(True), '.true.')
        self.assertEqual(nml._f90repr(False), '.false.')
        self.assertEqual(nml._f90repr('abc'), "'abc'")

        for ptype in ({}, [], set()):
            self.assertRaises(ValueError, nml._f90repr, ptype)
github marshallward / f90nml / f90nml / namelist.py View on Github external
def _write_nmlgrp(self, grp_name, grp_vars, nml_file, sort=False):
        """Write namelist group to target file."""
        if self._newline:
            print(file=nml_file)
        self._newline = True

        if self.uppercase:
            grp_name = grp_name.upper()

        if sort:
            grp_vars = Namelist(sorted(grp_vars.items(), key=lambda t: t[0]))

        print('&{0}'.format(grp_name), file=nml_file)

        for v_name, v_val in grp_vars.items():

            v_start = grp_vars.start_index.get(v_name, None)

            for v_str in self._var_strings(v_name, v_val, v_start=v_start):
                nml_line = self.indent + '{0}'.format(v_str)
                print(nml_line, file=nml_file)

        print('/', file=nml_file)
github marshallward / f90nml / f90nml / __init__.py View on Github external
This function is equivalent to the ``write`` function of the ``Namelist``
    object ``nml``.

    >>> nml.write('data.nml')

    By default, ``write`` will not overwrite an existing file.  To override
    this, use the ``force`` flag.

    >>> nml.write('data.nml', force=True)

    To alphabetically sort the ``Namelist`` keys, use the ``sort`` flag.

    >>> nml.write('data.nml', sort=True)
    """
    # Promote dicts to Namelists
    if not isinstance(nml, Namelist) and isinstance(nml, dict):
        nml_in = Namelist(nml)
    else:
        nml_in = nml

    nml_in.write(nml_path, force=force, sort=sort)
github marshallward / f90nml / f90nml / namelist.py View on Github external
v_start=v_start)
                var_strs.extend(v_strs)

        # Parse derived type contents
        elif isinstance(v_values, Namelist):
            for f_name, f_vals in v_values.items():
                v_title = '%'.join([v_name, f_name])

                v_start_new = v_values.start_index.get(f_name, None)

                v_strs = self._var_strings(v_title, f_vals,
                                           v_start=v_start_new)
                var_strs.extend(v_strs)

        # Parse an array of derived types
        elif is_nullable_list(v_values, Namelist):
            if not v_idx:
                v_idx = []

            i_s = v_start[::-1][len(v_idx)] if v_start else 1

            for idx, val in enumerate(v_values, start=i_s):

                # Skip any empty elements in a list of derived types
                if val is None:
                    continue

                v_title = v_name + '({0})'.format(idx)

                v_strs = self._var_strings(v_title, val)
                var_strs.extend(v_strs)
github marshallward / f90nml / f90nml / parser.py View on Github external
if vpar and isinstance(vpar, list):
                    # If new element is not a list, then assume it's the first
                    # element of the list.
                    if dt_idx is None:
                        dt_idx = self.default_start_index

                    try:
                        v_parent = vpar[dt_idx]
                    except IndexError:
                        v_parent = Namelist()
                elif vpar:
                    v_parent = vpar
                else:
                    v_parent = Namelist()
            else:
                v_parent = Namelist()
                parent[v_name] = v_parent

            self._update_tokens()
            self._update_tokens()

            v_att, v_att_vals = self._parse_variable(
                v_parent,
                patch_nml=v_patch_nml
            )

            next_value = Namelist()
            next_value[v_att] = v_att_vals
            self._append_value(v_values, next_value, v_idx)

        else:
            # Construct the variable array
github marshallward / f90nml / f90nml / namelist.py View on Github external
"""Case-insensitive interface to OrderedDict.

        Python dict inputs to the Namelist, such as derived types, are also
        converted into Namelists.
        """
        if isinstance(value, dict) and not isinstance(value, Namelist):
            value = Namelist(value,
                             default_start_index=self.default_start_index)

        elif is_nullable_list(value, dict):
            for i, v in enumerate(value):
                if isinstance(v, Namelist) or v is None:
                    value[i] = v
                else:
                    # value is a non-Namelist dict
                    value[i] = Namelist(
                        v,
                        default_start_index=self.default_start_index
                    )

        super(Namelist, self).__setitem__(key.lower(), value)
github marshallward / f90nml / f90nml / namelist.py View on Github external
def __setitem__(self, key, value):
        """Case-insensitive interface to OrderedDict.

        Python dict inputs to the Namelist, such as derived types, are also
        converted into Namelists.
        """
        if isinstance(value, dict) and not isinstance(value, Namelist):
            value = Namelist(value,
                             default_start_index=self.default_start_index)

        elif is_nullable_list(value, dict):
            for i, v in enumerate(value):
                if isinstance(v, Namelist) or v is None:
                    value[i] = v
                else:
                    # value is a non-Namelist dict
                    value[i] = Namelist(
                        v,
                        default_start_index=self.default_start_index
                    )

        super(Namelist, self).__setitem__(key.lower(), value)