In 1999 NASA lost the Mars Climate Orbiter because one team fed pound-force-seconds into software that expected newton-seconds. Every developer who writes scientific code carries that story in the back of their head, because unit bugs are silent: the numbers look plausible, the tests pass, and the spacecraft crashes. Astropy โ the foundation library of Python astronomy โ attacked this problem at the deepest possible layer: not with a validator you must remember to call, but by making the array itself refuse to be wrong.
The pain does not stop at units. Astronomers inherit file formats from the punch-card era: FITS headers are sequences of exactly 80-character records that must be padded, continued and parsed with cryptographic care. They juggle time scales that differ by tens of seconds (UTC ticks with leap seconds, TDB drifts against UTC by geometry and relativity), and they convert between coordinate frames โ ICRS, Galactic, AltAz โ whose relationships form a web, not a ladder. Hand-rolling any of this is how papers end up with corrections.
So in this tour we read the actual source of astropy/astropy on its main branch (version 8.0.2, released 2026-10-15) rather than the tutorials. We follow four load-bearing subsystems โ the units engine, the coordinate transform graph, FITS I/O, and the table/time layer โ using two diagrams generated from the real file tree. If you want to understand why scientific Python feels so solid, the answers are in these files.
Astropy overview: five subsystems orbit around one idea โ a unit-carrying ndarray shared by everything from physical constants to timestamps.
Reading the overview from left to right:
- UnitBase, L77 is the abstract root of every unit object; names, parsing and equivalency attachment hang off this one class.
- Quantity, L353 subclasses numpyโs
ndarraydirectly, so a unit rides along with every element of every array. - BaseCoordinateFrame, L406 turns frame data (longitude, latitude, distance, obstime) into declarative attribute descriptors.
- TransformGraph, L77 is a directed graph whose edges are registered conversions between frame classes.
- SkyCoord, L71 is the user-facing facade that infers frames and walks the transform graph for you.
- Card, L41 parses one 80-character FITS header record, including the notorious CONTINUE long-string scheme.
- HDUList, L242 is literally a
listsubclass that lazily streams Header/Data Units from disk. - Table, L628 is the column-oriented container that quietly accepts Quantity, Time and SkyCoord as columns.
- Time, L1892 stores every instant as a pair of doubles and routes scale conversions through a hand-written hop table.
Astropy detail: 32 classes and 35 relationships, from IrreducibleUnit and the VOUnit parser to CompImageHDU and the jd1/jd2 time base.
Units: an ndarray that refuses to be wrong
The cleverest decision in the codebase is also the shortest line: class Quantity(np.ndarray): at quantity.py L353. By subclassing ndarray instead of wrapping it, astropy gets numpyโs entire C-speed engine โ slicing, broadcasting, memory-mapped files โ while overriding ufunc dispatch so every addition and multiplication converts units first. A Quantity is not data with metadata; it is a numpy array, in every function that accepts one.
Above it sits a disciplined class tree in core.py. UnitBase at L77 is the root; IrreducibleUnit at L1931 marks base units like metre and second that cannot be decomposed; CompositeUnit at L2344 stores bases, powers and a scale factor, which is how km/s or erg/(cm2 s Hz) exist at all. The user-facing Unit class at L2208 is built with a custom _UnitMetaClass (L2057) that makes Unit('m/s') return a cached instance rather than a fresh object โ string parsing pays for itself once. All known units live in a _UnitRegistry (L1243), which context managers can swap out to temporarily enable equivalencies.
Unit strings themselves are a Tower of Babel โ FITS files, the Virtual Observatory, the CDS standard and OGIP all spell units differently โ so astropy parses them with pluggable parsers registered in a class-level dict: Base.registry[cls.name] = cls at format/base.py L47. Eight formats ship in the tree: Generic (L401 in generic.py, with generated lexer tables), FITS (L20), VOUnit (L32), CDS (L28), OGIP (L37), plus Console, Latex and Unicode renderers. Non-convertible-but-related pairs โ like flux densities measured per frequency versus per wavelength โ are handled by equivalency factories such as parallax() at equivalencies.py L112, doppler_radio() at L350 and brightness_temperature() at L577, which inject context-specific conversion functions into the registry only while in scope. Even scipy is first-class: quantity_helper/scipy_special.py exists purely to register scipy.special ufuncs so Quantity arithmetic works with them, and physical constants in constants/constant.py are themselves Quantities โ class Constant(Quantity, metaclass=ConstantMeta) at L92 โ each carrying uncertainty and a CODATA reference year.
Coordinates: a graph, not a ladder
Coordinate conversion is where naive designs die, because the relationships are not hierarchical: ICRS to Galactic needs a rotation, ICRS to AltAz needs your position and the current time, FK4 needs E-terms of aberration. Astropy models this honestly as a graph. The module-level frame_transform_graph = TransformGraph() at baseframe.py L57 is the single object every built-in frame registers into, and TransformGraph (L77 in transformations/graph.py) composes registered edges by path search when you call transform_to.
A frame is data declared as descriptors. BaseCoordinateFrame (L406) collects frame_attributes (assigned at L519) โ longitude, latitude, distance, obstime, location โ and each attribute is validated by a descriptor from attributes.py: the base Attribute at L120, TimeAttribute at L264, QuantityAttribute at L402 and CoordinateAttribute at L551. That is why passing a string where an EarthLocation is required fails with a precise error instead of garbage downstream. Transforms themselves descend from the abstract CoordinateTransform (L17 in transformations/base.py); some are pure matrix rotations (StaticMatrixTransform), others are functions wrapping ERFA, the C library that implements IAU standards.
Seventeen frame-definition modules live under builtin_frames/ โ ICRS (L12 in icrs.py, subclassing BaseRADecFrame), FK5, Galactic, AltAz, CIRS, ITRS, Galactocentric and friends โ each importing the shared graph and registering its edges at import time. builtin_frames/__init__.py even auto-generates the documentation table by calling make_transform_graph_docs(frame_transform_graph) (L239). SkyCoord (L71 in sky_coordinate.py, 1651 lines) is the UX layer on top: it infers which frame you meant, parses strings like โ180d0m0sโ, supports cross-matching, and hides the graph walk behind transform_to.
FITS: 80 columns or bust
FITS was standardized when cards were literally punched, and the format never forgives you: every header record is CARD_LENGTH = 80 (card.py L21), blocks are BLOCK_SIZE = 2880 (header.py L26), keywords longer than eight characters need the HIERARCH convention, and long string values spill into CONTINUE cards. The Card class (L41) is 1163 lines of exactly this archaeology, including _commentary_keywords at L154 โ the set of COMMENT, HISTORY and blank keywords that get appended rather than replaced. Header (L55) is an ordered mapping over those cards, and HDUList (L242) subclasses Pythonโs list so users index and iterate HDUs while the class handles lazy loading and 2880-byte block padding on write.
The HDU hierarchy in hdu/base.py is textbook: _BaseHDU (L133) defines the header/data contract, _ValidHDU (L850) adds verification and data loading, and ExtensionHDU (L1530) marks anything that can follow the primary HDU. Images get PrimaryHDU (L1105 in image.py) and ImageHDU (L1213) โ the latter with a Section class (L983) that reads cutouts without loading the whole array. Compression is where astropy stops pretending Python is fast enough: CompImageHDU (L46 in hdu/compressed/compressed.py) tiles images through vendored C codecs โ ricecomp.h, pliocomp.h and fits_hcompress.h sit in hdu/compressed/src/. Cython (/cython/) appears elsewhere too: io/fits/_utils.pyx and table/_column_mixins.pyx are compiled extensions, part of a build that also vendors cfitsio, wcslib and expat under cextern/.
From 80-byte cards to jd1/jd2 doubles: build facts in the code
The time subsystem shows the same โsmall numbers, hard rulesโ engineering. Every instant in Time is stored as two float64s โ jd1/jd2 โ a two-part Julian date that preserves sub-microsecond precision where a single double would lose it; TimeBase (L482) owns that layout, and import erfa at L20 pulls in the C machinery that does the actual scale math. The set of scales is a hard tuple at L74: STANDARD_TIME_SCALES = ("tai", "tcb", "tcg", "tdb", "tt", "ut1", "utc"), grouped geocentric/barycentric/rotational at L97-99. Conversions that ERFA cannot do directly are routed through MULTI_HOPS (L80), a dict of 15 hand-picked intermediate stops โ converting TCB to UTC, for instance, must hop through tdb, tt, tai in order. Parsing is delegated to formats.py: 36 Time-prefixed format classes (TimeJD at L607, TimeFromEpoch at L743, TimeISO at L1977, TimeISOT at L2032) across 2327 lines, with a C accelerator in time/src/parse_times.c.
The table layer mirrors this: Table is 3882 lines (table.py L628) with TableColumns (an OrderedDict subclass, L243), QTable at L4514 that auto-promotes unit-bearing columns to Quantity, Column(BaseColumn) at column.py L1270 backed by the Cython mixins, and Row at L17. Metadata round-trips through YAML via get_yaml_from_table (L291 in meta.py) โ the backbone of ECSV interchange โ and dask arrays plug in as columns through DaskColumn(da.Array) (L14 in table/mixins/dask.py). Build-level facts: the project requires Python 3.12+ (pyproject.toml, L13), tracks about 2,100 files in the repo tree, and moves only in versioned steps โ 8.0.2 landed 2026-10-15 per CHANGES.rst.
Honest Limits
The source is honest about what it cannot do. UT1 depends on Earth-rotation tables that lag real time, so Enjoyed this post? Never miss out on future posts by following us Time scale conversions can require data downloads and are only as current as the IERS bulletin you have cached. Quantity makes wrong units loud, but it cannot make numpy ufuncs that astropy has not registered unit-aware โ coverage is explicit, not magical, which is why the scipy_special helper module exists at all. The transform graph computes paths at runtime, so first conversions between exotic frame pairs carry Python overhead, and AltAz-class frames are only as good as the ephemerides and site locations you supply. FITS Card handles CONTINUE and HIERARCH, but the formatโs 80-column heritage means long metadata is inherently hacky; that is a standards constraint, not an implementation one. And the table layerโs flexibility โ any mixin can be a column โ means some operations fall back to slower paths when columns are not plain ndarrays. None of this is hidden: the checks, registries and vendored C sources in the tree are where the guarantees live, which is exactly what makes the library trustworthy enough to sit under modern astronomy.