Add package_tools module for exporter

This commit is contained in:
arofarn 2021-06-28 13:50:17 +02:00
parent 0a7ed162d7
commit adaf8b11b9
3 changed files with 119 additions and 50 deletions

View File

@ -3,12 +3,10 @@
# #
# SPDX-License-Identifier: BSD-3-Clause # SPDX-License-Identifier: BSD-3-Clause
import umetpy.constants import umetpy.constants as mpconsts
# pylint: disable=eval-used # pylint: disable=eval-used
print("List of all constants:\n") print("List of all constants:\n")
for cst in dir(umetpy.constants): for cst in dir(mpconsts):
if cst[0] != "_": if cst[0] != "_":
print( print("{:30s} = {:.12f}".format(cst, eval("{}.{}".format("mpconsts", cst))))
"{:25s} = {:f}".format(cst, eval("{}.{}".format("umetpy.constants", cst)))
)

View File

@ -4,7 +4,7 @@
# pylint: disable=line-too-long # pylint: disable=line-too-long
r"""A collection of meteorologically significant constant and thermophysical property values. r"""A collection of meteorologically significant constants and thermophysical property values.
Earth Earth
----- -----
@ -75,7 +75,12 @@ molecular_weight_ratio :math:`\epsilon` epsilon :math:`\text{None}`
# pylint: enable=line-too-long # pylint: enable=line-too-long
# pylint: disable=invalid-name # pylint: disable=invalid-name
from .package_tools import Exporter
exporter = Exporter(globals())
# Export all the variables defined in this block
with exporter:
# Earth # Earth
earth_gravity = g = 9.80665 # 'm / s^2' earth_gravity = g = 9.80665 # 'm / s^2'
Re = earth_avg_radius = 6371008.7714 # 'm' Re = earth_avg_radius = 6371008.7714 # 'm'
@ -115,7 +120,7 @@ Cp_d = dry_air_spec_heat_press = (
) )
Cv_d = dry_air_spec_heat_vol = Cp_d / dry_air_spec_heat_ratio Cv_d = dry_air_spec_heat_vol = Cp_d / dry_air_spec_heat_ratio
# TODO : check unit conversion # TODO : check unit conversion
# rho_d = dry_air_density_stp = (1000., 'mbar') / (Rd * 273.15, 'K'))) # 'kg / m^3' rho_d = dry_air_density_stp = 1000.0 / (Rd * 273.15) # 'kg / m^3'
# General meteorology constants # General meteorology constants
P0 = pot_temp_ref_press = 1000.0 # 'mbar' P0 = pot_temp_ref_press = 1000.0 # 'mbar'
@ -124,3 +129,6 @@ kappa = poisson_exponent = Rd / Cp_d # 'dimensionless'
gamma_d = dry_adiabatic_lapse_rate = g / Cp_d gamma_d = dry_adiabatic_lapse_rate = g / Cp_d
# TODO : check unit conversion # TODO : check unit conversion
epsilon = molecular_weight_ratio = Mw / Md # 'dimensionless' epsilon = molecular_weight_ratio = Mw / Md # 'dimensionless'
del exporter
del Exporter

63
umetpy/package_tools.py Normal file
View File

@ -0,0 +1,63 @@
# Copyright (c) 2015,2018,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Collection of tools for managing the package."""
# Used to specify functions that should be exported--i.e. added to __all__
# Inspired by David Beazley and taken from python-ideas:
# https://mail.python.org/pipermail/python-ideas/2014-May/027824.html
__all__ = ("Exporter",)
class Exporter:
"""Manages exporting of symbols from the module.
Grabs a reference to `globals()` for a module and provides a decorator to add
functions and classes to `__all__` rather than requiring a separately maintained list.
Also provides a context manager to do this for instances by adding all instances added
within a block to `__all__`.
"""
def __init__(self, globls):
"""Initialize the Exporter."""
self.globls = globls
self.exports = globls.setdefault("__all__", [])
def export(self, defn):
"""Declare a function or class as exported."""
self.exports.append(defn.__name__)
return defn
def __enter__(self):
"""Start a block tracking all instances created at global scope."""
# pylint: disable=attribute-defined-outside-init
self.start_vars = set(self.globls)
# pylint: enable=attribute-defined-outside-init
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the instance tracking block."""
self.exports.extend(set(self.globls) - self.start_vars)
del self.start_vars
def set_module(globls):
"""Set the module for all functions in ``__all__``.
This sets the ``__module__`` attribute of all items within the ``__all__`` list
for the calling module.
This supports our hoisting of functions out of individual modules, which are
considered implementation details, into the namespace of the top-level subpackage.
Parameters
----------
globls : Dict[str, object]
Mapping of all global variables for the module. This contains all needed
python special ("dunder") variables needed to be modified.
"""
for item in globls["__all__"]:
obj = globls[item]
if hasattr(obj, "__module__"):
obj.__module__ = globls["__name__"]