Astroy I/O打字 (astropy.io.typing )#

astropy.io 方法提供类型批注。 astropy.io.typing 模块。这些类型批注允许用户在使用I/O时指定预期的变量类型、函数参数和返回值。通过使用类型批注,开发人员可以提高代码的可读性,及早发现潜在的与类型相关的错误,并启用更好的代码文档和工具支持。

例如,下面的函数使用类型批注指定 filename 参数可以是任何类型的类似路径的对象(例如,字符串、字节字符串或pathlib.Path对象)。

from astropy.io import fits
from astropy.io.typing import PathLike

def read_fits_file(filename: PathLike) -> fits.HDUList:
     return fits.open(filename)

这个 astropy.io.typing 模块还为支持读写的类似文件的对象提供类型别名。下面的示例使用 ReadableFileLike 键入别名以指定 fileobj 参数可以是任何支持读取的类似文件的对象。使用 TypeVar 函数的返回类型被指定为与类文件对象可以读取的类型相同。

from typing import TypeVar
from astropy.io.typing import ReadableFileLike

R = TypeVar('R')  # type of object returned by fileobj.read()

def read_from_file(fileobj: ReadableFileLike[R]) -> R:
     """Reads from a file-like object and returns the result."""
     return fileobj.read()

参考/API#

Asterpy.io.打字模块#

为以下项键入批注 astropy.io

这些是与I/O相关的函数和类的类型注释。一些类型对象也可以用作运行时可检查对象 Protocol 物体。

Classes#

ReadableFileLike(*args, **kwargs)

支持使用方法读取的类似文件的对象 read

WriteableFileLike(*args, **kwargs)

支持使用方法写入的类似文件的对象 write

类继承图#

Inheritance diagram of astropy.io.typing.ReadableFileLike, astropy.io.typing.WriteableFileLike