示例#1
0
文件: runner.py 项目: MaxNoe/astropy
    def make_test_runner_in(cls, path):
        """
        Constructs a `TestRunner` to run in the given path, and returns a
        ``test()`` function which takes the same arguments as
        `TestRunner.run_tests`.

        The returned ``test()`` function will be defined in the module this
        was called from.  This is used to implement the ``astropy.test()``
        function (or the equivalent for affiliated packages).
        """

        runner = cls(path)

        @wraps(runner.run_tests, ('__doc__',), exclude_args=('self',))
        def test(**kwargs):
            return runner.run_tests(**kwargs)

        module = find_current_module(2)
        if module is not None:
            test.__module__ = module.__name__

        # A somewhat unusual hack, but delete the attached __wrapped__
        # attribute--although this is normally used to tell if the function
        # was wrapped with wraps, on some version of Python this is also
        # used to determine the signature to display in help() which is
        # not useful in this case.  We don't really care in this case if the
        # function was wrapped either
        if hasattr(test, '__wrapped__'):
            del test.__wrapped__

        test.__test__ = False
        return test
示例#2
0
    def make_test_runner_in(cls, path):
        """
        Constructs a `TestRunner` to run in the given path, and returns a
        ``test()`` function which takes the same arguments as
        `TestRunner.run_tests`.

        The returned ``test()`` function will be defined in the module this
        was called from.  This is used to implement the ``astropy.test()``
        function (or the equivalent for affiliated packages).
        """

        runner = cls(path)

        @wraps(runner.run_tests, ('__doc__', ))
        def test(**kwargs):
            return runner.run_tests(**kwargs)

        module = find_current_module(2)
        if module is not None:
            test.__module__ = module.__name__

        # A somewhat unusual hack, but delete the attached __wrapped__
        # attribute--although this is normally used to tell if the function
        # was wrapped with wraps, on some version of Python this is also
        # used to determine the signature to display in help() which is
        # not useful in this case.  We don't really care in this case if the
        # function was wrapped either
        if hasattr(test, '__wrapped__'):
            del test.__wrapped__

        test.__test__ = False
        return test
示例#3
0
文件: log.py 项目: danhey/thejoker
    def makeRecord(self,
                   name,
                   level,
                   pathname,
                   lineno,
                   msg,
                   args,
                   exc_info,
                   func=None,
                   extra=None,
                   sinfo=None):
        if extra is None:
            extra = {}
        if 'origin' not in extra:
            current_module = find_current_module(1, finddiff=[True, 'logging'])
            if current_module is not None:
                extra['origin'] = current_module.__name__
            else:
                extra['origin'] = 'unknown'

        return Logger.makeRecord(self,
                                 name,
                                 level,
                                 pathname,
                                 lineno,
                                 msg,
                                 args,
                                 exc_info,
                                 func=func,
                                 extra=extra,
                                 sinfo=sinfo)
示例#4
0
def set_enabled_constants(modname):
    """
    Context manager to temporarily set values in the ``constants``
    namespace to an older version.
    See :ref:`astropy-constants-prior` for usage.

    Parameters
    ----------
    modname : {'astropyconst13', 'astropyconst20'}
        Name of the module containing an older version.

    """

    # Re-import here because these were deleted from namespace on init.
    import importlib
    import warnings
    from astropy.utils import find_current_module
    from . import utils as _utils

    try:
        modmodule = importlib.import_module('.constants.' + modname, 'astropy')
        codata_context = modmodule.codata
        iaudata_context = modmodule.iaudata
    except ImportError as exc:
        exc.args += (
            'Context manager does not currently handle {}'.format(modname), )
        raise

    module = find_current_module()

    # Ignore warnings about "Constant xxx already has a definition..."
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore',
                                'Constant .*already has a definition')
        _utils._set_c(codata_context,
                      iaudata_context,
                      module,
                      not_in_module_only=False,
                      set_class=True)

    try:
        yield
    finally:
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore',
                                    'Constant .*already has a definition')
            _utils._set_c(codata,
                          iaudata,
                          module,
                          not_in_module_only=False,
                          set_class=True)
示例#5
0
    def __init__(self,
                 defaultvalue='',
                 description=None,
                 cfgtype=None,
                 module=None,
                 aliases=None):
        from astropy.utils import isiterable

        if module is None:
            module = find_current_module(2)
            if module is None:
                msg1 = 'Cannot automatically determine get_config module, '
                msg2 = 'because it is not called from inside a valid module'
                raise RuntimeError(msg1 + msg2)
            else:
                module = module.__name__

        self.module = module
        self.description = description
        self.__doc__ = description

        # now determine cfgtype if it is not given
        if cfgtype is None:
            if (isiterable(defaultvalue)
                    and not isinstance(defaultvalue, str)):
                # it is an options list
                dvstr = [str(v) for v in defaultvalue]
                cfgtype = 'option(' + ', '.join(dvstr) + ')'
                defaultvalue = dvstr[0]
            elif isinstance(defaultvalue, bool):
                cfgtype = 'boolean'
            elif isinstance(defaultvalue, int):
                cfgtype = 'integer'
            elif isinstance(defaultvalue, float):
                cfgtype = 'float'
            elif isinstance(defaultvalue, str):
                cfgtype = 'string'
                defaultvalue = str(defaultvalue)

        self.cfgtype = cfgtype

        self._validate_val(defaultvalue)
        self.defaultvalue = defaultvalue

        if aliases is None:
            self.aliases = []
        elif isinstance(aliases, str):
            self.aliases = [aliases]
        else:
            self.aliases = aliases
示例#6
0
def set_enabled_constants(modname):
    """
    Context manager to temporarily set values in the ``constants``
    namespace to an older version.
    See :ref:`astropy-constants-prior` for usage.

    Parameters
    ----------
    modname : {'astropyconst13'}
        Name of the module containing an older version.

    """

    # Re-import here because these were deleted from namespace on init.
    import warnings
    from astropy.utils import find_current_module
    from . import utils as _utils

    # NOTE: Update this when default changes.
    if modname == 'astropyconst13':
        from .astropyconst13 import codata2010 as codata
        from .astropyconst13 import iau2012 as iaudata
    else:
        raise ValueError(
            'Context manager does not currently handle {}'.format(modname))

    module = find_current_module()

    # Ignore warnings about "Constant xxx already has a definition..."
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        _utils._set_c(codata,
                      iaudata,
                      module,
                      not_in_module_only=False,
                      set_class=True)

    try:
        yield
    finally:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            # NOTE: Update this when default changes.
            _utils._set_c(codata2014,
                          iau2015,
                          module,
                          not_in_module_only=False,
                          set_class=True)
示例#7
0
    def __init__(self, defaultvalue='', description=None, cfgtype=None,
                 module=None, aliases=None):
        from astropy.utils import isiterable

        if module is None:
            module = find_current_module(2)
            if module is None:
                msg1 = 'Cannot automatically determine get_config module, '
                msg2 = 'because it is not called from inside a valid module'
                raise RuntimeError(msg1 + msg2)
            else:
                module = module.__name__

        self.module = module
        self.description = description
        self.__doc__ = description

        # now determine cfgtype if it is not given
        if cfgtype is None:
            if (isiterable(defaultvalue) and not
                    isinstance(defaultvalue, str)):
                # it is an options list
                dvstr = [str(v) for v in defaultvalue]
                cfgtype = 'option(' + ', '.join(dvstr) + ')'
                defaultvalue = dvstr[0]
            elif isinstance(defaultvalue, bool):
                cfgtype = 'boolean'
            elif isinstance(defaultvalue, int):
                cfgtype = 'integer'
            elif isinstance(defaultvalue, float):
                cfgtype = 'float'
            elif isinstance(defaultvalue, str):
                cfgtype = 'string'
                defaultvalue = str(defaultvalue)

        self.cfgtype = cfgtype

        self._validate_val(defaultvalue)
        self.defaultvalue = defaultvalue

        if aliases is None:
            self.aliases = []
        elif isinstance(aliases, str):
            self.aliases = [aliases]
        else:
            self.aliases = aliases
示例#8
0
def _set_enabled_constants(modname: T.Union[str, bool]):
    """_set_enabled_constants."""
    try:
        if isinstance(modname, bool):
            codata_context = _codata
            iaudata_context = _iaudata

        else:
            modmodule = importlib.import_module(".constants." + modname,
                                                "astropy")
            codata_context = modmodule.codata
            iaudata_context = modmodule.iaudata

    except ImportError as exc:
        exc.args += (
            "Context manager does not currently handle {}".format(modname), )
        raise

    module = find_current_module()

    # Ignore warnings about "Constant xxx already has a definition..."
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                "Constant .*already has a definition")
        consts.utils._set_c(
            codata_context,
            iaudata_context,
            module,
            not_in_module_only=False,
            set_class=True,
        )

    try:
        yield
    finally:
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore",
                                    "Constant .*already has a definition")
            consts.utils._set_c(
                _codata,
                _iaudata,
                module,
                not_in_module_only=False,
                set_class=True,
            )
示例#9
0
文件: log.py 项目: adrn/SuperFreq
    def makeRecord(self, name, level, pathname, lineno, msg, args, exc_info,
                   func=None, extra=None, sinfo=None):
        if extra is None:
            extra = {}
        if 'origin' not in extra:
            current_module = find_current_module(1, finddiff=[True, 'logging'])
            if current_module is not None:
                extra['origin'] = current_module.__name__
            else:
                extra['origin'] = 'unknown'

        if PY3:
            return Logger.makeRecord(self, name, level, pathname, lineno, msg,
                                     args, exc_info, func=func, extra=extra,
                                     sinfo=sinfo)
        else:
            return Logger.makeRecord(self, name, level, pathname, lineno, msg,
                                     args, exc_info, func=func, extra=extra)
示例#10
0
        def _monkey_patch_1_0_1_ConfigItem__init__(
                self, defaultvalue='', description=None, cfgtype=None,
                module=None, aliases=None):
            if module is None:
                from astropy.utils import find_current_module
                module = find_current_module(2)
                if module is None:
                    msg1 = 'Cannot automatically determine get_config module, '
                    msg2 = 'because it is not called from inside a valid module'
                    raise RuntimeError(msg1 + msg2)
                else:
                    module = module.__name__

            return _existing_ConfigItem__init__(
                self,
                defaultvalue=defaultvalue,
                description=description,
                cfgtype=cfgtype,
                module=module,
                aliases=aliases)
示例#11
0
        def _monkey_patch_1_0_1_ConfigItem__init__(self,
                                                   defaultvalue='',
                                                   description=None,
                                                   cfgtype=None,
                                                   module=None,
                                                   aliases=None):
            if module is None:
                from astropy.utils import find_current_module
                module = find_current_module(2)
                if module is None:
                    msg1 = 'Cannot automatically determine get_config module, '
                    msg2 = 'because it is not called from inside a valid module'
                    raise RuntimeError(msg1 + msg2)
                else:
                    module = module.__name__

            return _existing_ConfigItem__init__(self,
                                                defaultvalue=defaultvalue,
                                                description=description,
                                                cfgtype=cfgtype,
                                                module=module,
                                                aliases=aliases)
示例#12
0
def test_imports():
    """
    This just imports all modules in astropy, making sure they don't have any
    dependencies that sneak through
    """

    from astropy.utils import find_current_module

    pkgornm = find_current_module(1).__name__.split('.')[0]

    if isinstance(pkgornm, str):
        package = pkgutil.get_loader(pkgornm).load_module(pkgornm)
    elif (isinstance(pkgornm, types.ModuleType) and
            '__init__' in pkgornm.__file__):
        package = pkgornm
    else:
        msg = 'test_imports is not determining a valid package/package name'
        raise TypeError(msg)

    if hasattr(package, '__path__'):
        pkgpath = package.__path__
    elif hasattr(package, '__file__'):
        pkgpath = os.path.split(package.__file__)[0]
    else:
        raise AttributeError('package to generate config items for does not '
                             'have __file__ or __path__')

    prefix = package.__name__ + '.'

    def onerror(name):
        # A legitimate error occurred in a module that wasn't excluded
        raise

    for imper, nm, ispkg in pkgutil.walk_packages(pkgpath, prefix,
                                                  onerror=onerror):
        imper.find_module(nm)
示例#13
0
def get_config(packageormod=None, reload=False):
    """ Gets the configuration object or section associated with a particular
    package or module.

    Parameters
    -----------
    packageormod : str or None
        The package for which to retrieve the configuration object. If a
        string, it must be a valid package name, or if `None`, the package from
        which this function is called will be used.

    reload : bool, optional
        Reload the file, even if we have it cached.

    Returns
    -------
    cfgobj : ``configobj.ConfigObj`` or ``configobj.Section``
        If the requested package is a base package, this will be the
        ``configobj.ConfigObj`` for that package, or if it is a subpackage or
        module, it will return the relevant ``configobj.Section`` object.

    Raises
    ------
    RuntimeError
        If ``packageormod`` is `None`, but the package this item is created
        from cannot be determined.
    """
    if packageormod is None:
        packageormod = find_current_module(2)
        if packageormod is None:
            msg1 = 'Cannot automatically determine get_config module, '
            msg2 = 'because it is not called from inside a valid module'
            raise RuntimeError(msg1 + msg2)
        else:
            packageormod = packageormod.__name__

    packageormodspl = packageormod.split('.')
    rootname = packageormodspl[0]
    secname = '.'.join(packageormodspl[1:])

    cobj = _cfgobjs.get(rootname, None)

    if cobj is None or reload:
        if _ASTROPY_SETUP_:
            # There's no reason to use anything but the default config
            cobj = configobj.ConfigObj(interpolation=False)
        else:
            cfgfn = None
            try:
                # This feature is intended only for use by the unit tests
                if _override_config_file is not None:
                    cfgfn = _override_config_file
                else:
                    cfgfn = path.join(get_config_dir(), rootname + '.cfg')
                cobj = configobj.ConfigObj(cfgfn, interpolation=False)
            except OSError as e:
                msg = ('Configuration defaults will be used due to ')
                errstr = '' if len(e.args) < 1 else (':' + str(e.args[0]))
                msg += e.__class__.__name__ + errstr
                msg += ' on {0}'.format(cfgfn)
                warn(ConfigurationMissingWarning(msg))

                # This caches the object, so if the file becomes accessible, this
                # function won't see it unless the module is reloaded
                cobj = configobj.ConfigObj(interpolation=False)

        _cfgobjs[rootname] = cobj

    if secname:  # not the root package
        if secname not in cobj:
            cobj[secname] = {}
        return cobj[secname]
    else:
        return cobj
示例#14
0
from . import utils as _utils  # noqa

# for updating the constants module docstring
_lines = [
    'The following constants are available:\n',
    '========== ============== ================ =========================',
    '   Name        Value            Unit       Description',
    '========== ============== ================ =========================',
]

# Catch warnings about "already has a definition in the None system"
with warnings.catch_warnings():
    warnings.filterwarnings('ignore', 'Constant .*already has a definition')
    _utils._set_c(codata,
                  iaudata,
                  find_current_module(),
                  not_in_module_only=True,
                  doclines=_lines,
                  set_class=True)

_lines.append(_lines[1])

if __doc__ is not None:
    __doc__ += '\n'.join(_lines)


# TODO: Re-implement in a way that is more consistent with astropy.units.
#       See https://github.com/astropy/astropy/pull/7008 discussions.
@contextmanager
def set_enabled_constants(modname):
    """
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v1.3 and earlier.
See :mod:`astropy.constants` for a complete listing of constants
defined in Astropy.
"""
from astropy.utils import find_current_module
from . import utils as _utils
from . import codata2010, iau2012

_utils._set_c(codata2010, iau2012, find_current_module())

# Clean up namespace
del find_current_module
del _utils
示例#16
0
def get_config(packageormod=None, reload=False):
    """ Gets the configuration object or section associated with a particular
    package or module.

    Parameters
    -----------
    packageormod : str or None
        The package for which to retrieve the configuration object. If a
        string, it must be a valid package name, or if `None`, the package from
        which this function is called will be used.

    reload : bool, optional
        Reload the file, even if we have it cached.

    Returns
    -------
    cfgobj : ``configobj.ConfigObj`` or ``configobj.Section``
        If the requested package is a base package, this will be the
        ``configobj.ConfigObj`` for that package, or if it is a subpackage or
        module, it will return the relevant ``configobj.Section`` object.

    Raises
    ------
    RuntimeError
        If ``packageormod`` is `None`, but the package this item is created
        from cannot be determined.
    """
    if packageormod is None:
        packageormod = find_current_module(2)
        if packageormod is None:
            msg1 = 'Cannot automatically determine get_config module, '
            msg2 = 'because it is not called from inside a valid module'
            raise RuntimeError(msg1 + msg2)
        else:
            packageormod = packageormod.__name__

    packageormodspl = packageormod.split('.')
    rootname = packageormodspl[0]
    secname = '.'.join(packageormodspl[1:])

    cobj = _cfgobjs.get(rootname, None)

    if cobj is None or reload:
        cfgfn = None
        try:
            # This feature is intended only for use by the unit tests
            if _override_config_file is not None:
                cfgfn = _override_config_file
            else:
                cfgfn = path.join(get_config_dir(), rootname + '.cfg')
            cobj = configobj.ConfigObj(cfgfn, interpolation=False)
        except OSError as e:
            msg = ('Configuration defaults will be used due to ')
            errstr = '' if len(e.args) < 1 else (':' + str(e.args[0]))
            msg += e.__class__.__name__ + errstr
            msg += f' on {cfgfn}'
            warn(ConfigurationMissingWarning(msg))

            # This caches the object, so if the file becomes accessible, this
            # function won't see it unless the module is reloaded
            cobj = configobj.ConfigObj(interpolation=False)

        _cfgobjs[rootname] = cobj

    if secname:  # not the root package
        if secname not in cobj:
            cobj[secname] = {}
        return cobj[secname]
    else:
        return cobj
示例#17
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v4.0.
See :mod:`astropy.constants` for a complete listing of constants defined
in Astropy.
"""
import warnings

from astropy.utils import find_current_module
from . import utils as _utils
from . import codata2018, iau2015

codata = codata2018
iaudata = iau2015

_utils._set_c(codata, iaudata, find_current_module())

# Overwrite the following for consistency.
# https://github.com/astropy/astropy/issues/8920
with warnings.catch_warnings():
    warnings.filterwarnings('ignore', 'Constant .*already has a definition')

    # Solar mass (derived from mass parameter and gravitational constant)
    M_sun = iau2015.IAU2015(
        'M_sun',
        "Solar mass",
        iau2015.GM_sun.value / codata2018.G.value,
        'kg', ((codata2018.G.uncertainty / codata2018.G.value) *
               (iau2015.GM_sun.value / codata2018.G.value)),
        f"IAU 2015 Resolution B 3 + {codata2018.G.reference}",
        system='si')
示例#18
0
def get_config(packageormod=None, reload=False, rootname=None):
    """ Gets the configuration object or section associated with a particular
    package or module.

    Parameters
    ----------
    packageormod : str or None
        The package for which to retrieve the configuration object. If a
        string, it must be a valid package name, or if ``None``, the package from
        which this function is called will be used.

    reload : bool, optional
        Reload the file, even if we have it cached.

    rootname : str or None
        Name of the root configuration directory. If ``None`` and
        ``packageormod`` is ``None``, this defaults to be the name of
        the package from which this function is called. If ``None`` and
        ``packageormod`` is not ``None``, this defaults to ``astropy``.

    Returns
    -------
    cfgobj : ``configobj.ConfigObj`` or ``configobj.Section``
        If the requested package is a base package, this will be the
        ``configobj.ConfigObj`` for that package, or if it is a subpackage or
        module, it will return the relevant ``configobj.Section`` object.

    Raises
    ------
    RuntimeError
        If ``packageormod`` is `None`, but the package this item is created
        from cannot be determined.
    """

    if packageormod is None:
        packageormod = find_current_module(2)
        if packageormod is None:
            msg1 = 'Cannot automatically determine get_config module, '
            msg2 = 'because it is not called from inside a valid module'
            raise RuntimeError(msg1 + msg2)
        else:
            packageormod = packageormod.__name__

        _autopkg = True

    else:
        _autopkg = False

    packageormodspl = packageormod.split('.')
    pkgname = packageormodspl[0]
    secname = '.'.join(packageormodspl[1:])

    if rootname is None:
        if _autopkg:
            rootname = pkgname
        else:
            rootname = 'astropy'  # so we don't break affiliated packages

    cobj = _cfgobjs.get(pkgname, None)

    if cobj is None or reload:
        cfgfn = None
        try:
            # This feature is intended only for use by the unit tests
            if _override_config_file is not None:
                cfgfn = _override_config_file
            else:
                cfgfn = path.join(get_config_dir(rootname=rootname),
                                  pkgname + '.cfg')
            cobj = configobj.ConfigObj(cfgfn, interpolation=False)
        except OSError:
            # This can happen when HOME is not set
            cobj = configobj.ConfigObj(interpolation=False)

        # This caches the object, so if the file becomes accessible, this
        # function won't see it unless the module is reloaded
        _cfgobjs[pkgname] = cobj

    if secname:  # not the root package
        if secname not in cobj:
            cobj[secname] = {}
        return cobj[secname]
    else:
        return cobj
示例#19
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v2.0.  See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
from astropy.utils import find_current_module
from . import utils as _utils
from . import codata2014, iau2015

_utils._set_c(codata2014, iau2015, find_current_module())

# Clean up namespace
del find_current_module
del _utils