Pautas del Empaquetado de Python

Esta versión de las Directrices de Empaquetamiento de Python están en efecto desde 2021 y representan una importante reescritura y cambio de paradigma. No todos los paquetes se actualizan para reflejar esto. Las directrices más antiguas se mantienen como referencia histórica, pero os nuevos paquetes NO DEBEN usarlas. Los paquetes existentes DEBEN migrar a las directrices actuales de Python:

Estas directrices solo soportan las versiones actuales de Fedora. Para versiones más antiguas (como en EPEL 8), consulte las directrices 201x-era.

Las dos [directrices en toda la distribución] de abajo se aplican a todo el software en Fedora que usa Python en tiempo de compilación o ejecución.

El resto de las Directrices se aplican a los paquetes que incluyen código que puede ser importado por la declaración import`de Python. Específicamente, esto es todos los paquetes que instalan archivos bajo `/usr/lib*/python*/.

Excepto para las dos “directrices de toda la Distribución”, estas Directrices no se aplican a utilidades o scripts simples de un solo archivo, especialmente si están incluidos con software no escrito en Python. Sin embargo, si una aplicación (por ejemplo, herramienta CLI, script o aplicación GUI) necesita una librería Python más compleja, la librería DEBERÍA ser empaquetada como una librería importable bajo estas directrices.

Un objetivo principal para el empaquetamiento de Python en Fedora es armonizar con el amplio ecosistema de Python, esto es, los estándares de la Python Packaging Authority (Autoridad de Empaquetamiento de Python) (PyPA) y el Python Package Index (Índice de Paquetes de Python) (PyPI). Los empaquetadores DEBERÍAN estar preparados para involucrarse con los proyectos de desarrollo para establecer las mejores prácticas como se describe aquí. Deseamos mejorar tanto Fedora y el ecosistema más amplio de Python.

Algunas herramientas de compilación (como CMake o autotools) puede que no trabajen con los últimos estándares PyPA todavía. (Por ejemplo, podrían generar directorios .egg-info en lugar de .dist-info.) Si bien los puntos normativos de este documento (DEBE/DEBERÍA) son independientes de la herramienta, muchos de los consejos prácticos y macros auxiliares no serán aplicables. Si esto le afecta, considere contactar con el Python SIG para orientación y/o seguir las directrices anteriores por el momento.
Python SIG de Fedora no solo desarrolla estas directrices, también está involucrado en los estándares PyPA y en las mejores prácticas de Python. Consulte lhttps://fedoraproject.org/wiki/SIGs/Python[la wiki] o lista de correo si necesita ayuda o desea ayudar.

Directrices en toda la Distribución

Dependencia en tiempo de compilación de python3-devel

Cada paquete que usa Python (en tiempo de ejecución y/o en tiempo de compilación) y/o instala módulos Python * DEBE* tener un dependencia en tiempo de compilación sobre python3-devel , incluso en el caso de que no se invoque realmente a Python durante el tiempo de compilación.

  • Si un paquete usa %pyproject_buildrequires en la sección %generate_buildrequires, estos añadirá automáticamente a requiere en compilación python3-devel.

  • De otro modo, un paquete debe incluir BuildRequires: python3-devel en su archivo .spec.

Tener solo una dependencia transitoria en tiempo de compilación sobre python3-devel no es suficiente. Si el paquete utiliza un intérprete de Python alternativo en lugar de python3 (por ejemplo, pypy,jython, python2.7), PUEDE requerir, en su lugar el paquete *-devel correspondiente.

El paquete *-devel incluye macros RPM relevantes. También puede habilitar controles automáticos o manuales: por ejemplo, los mantenedores de Python usan este requisito para listar los paquetes que usan Python de alguna manera y podrían ser afectados por cambios planeados.

Macros obligatorias

Las siguientes macros DEBEN ser utilizadas conde sean aplicables.

Las expansiones entre paréntesis se proporcionan sólo como referencia/ejemplo.

Las macros están definidas para usted en todas las versiones admitidas de Fedora y EPEL.

  • %{python3} (/usr/bin/python3): El intérprete de Python. Por ejemplo, esta macro debe utilizarse para invocar Python desde un script de archivo spec, pasado a scripts configure para seleccionar un ejecutable de Python, o utilizarse como %{python3} -m pip para ejecutar una herramienta basada en Python.

    Si el software empaquetado invoca Python en tiempo de ejecución (como opuesto a ejecutar Python para compilar/probarlo) quizá es necesario aprobar indicadores para %{python3} para aislarlo desde paquetes de usuario-instalado. Consulte [Shebang] para detalles.

  • %{python3_version} (p.ej. 3.9, 3.10): Versión del intérprete Python.

  • %{python3_version_nodots} (p.ej. 39, 310): versión del intérprete de Python sin el punto.

  • %{python3_sitelib} (p.ej. /usr/lib/python3.9/site-packages): donde módulos de Python puro son instalados.

  • %{python3_sitearch} (p.ej. /usr/lib64/python3.9/site-packages): donde módulos de extensión de Python (código nativo, p.ej. compilado desde C) están instalados.

El resto de este documento utilice estas macros, junto con %{_bindir} (/usr/bin/), en vez de los nombres de ruta en crudo.

Implementación de Python admite

Destinos CPython primario de Fedora, la implementación referencial del lenguaje Python. Generalmente utilizamos “Python” para significar CPython.

Implementaciones alternas como pypy están disponibles, pero actualmente carecen de herramientas y directrices comprensivas para empaquetado. Al dirigirse a ellos, no hay reglas estrictas (excepto las directrices generales de empaquetado de Fedora). Pero intenta respetar el espíritu de estas directrices. En caso de duda, considere consultar el SIG de Python.

Mantenimiento de versión de Python

Los paquetes de Fedora NO DEBEN depender de otras versiones del intérprete CPython que no sean el python3 actual.

En Fedora, las bibliotecas de Python son empaquetados para una versión única de Python, invocada como python3. Por ejemplo, en Fedora 32, python3 es Python 3.8.

En el pasado había múltiples pilas Python, por ejemplo`python3.7` y python2.7, instalables juntas en la misma máquina. Ese es también el caso de algunos proyectos que se basan en Fedora, como RHEL, EPEL y CentOS. Fedora podría volver a introducir pilas instalables en paralelo en el futuro (por ejemplo si un cambio a una nueva versión de Python necesita de un período de transición o si hay bastantes mantenedores interesados en que algo así aparezca).

Fedora incluye versiones alternativas del intérprete, por ejemplo, python2.7 o python3.5, pero estas están destinadas únicamente a desarrolladores que necesitan probar código upstream. Las correcciones de errores y seguridad para estos intérpretes solo cubren este caso de uso. Los paquetes como pip o tox, que permiten configurar entornos aislados e instalar paquetes de terceros en ellos, PUEDEN, como excepción a la regla anterior, utilizar estos intérpretes siempre que se coordine con los mantenedores del intérprete de Python correspondiente.

Nombrando

Los paquetes de Python tienen varios nombres diferentes, los cuales deben mantenerse sincronizados, pero que a veces difieren por razones históricas o prácticas. Son:

  • el nombre de paquete fuente de Fedora (o nombre de componente, %{name},

  • el nombre de compilación de RPM de Fedora,

  • el nombre de proyecto utilizado en PyPI o por pip, y

  • el nombre de módulo importable utilizando en Python (un único paquete puede tener múltiples módulos importables).

Algunos ejemplos (ambos bueno y peor):

Componente Fedora RPM compilado Nombre de Proyecto Módulo importable

python-requests

python3-requests

requests

requests

python-django

python3-django

Django

django

PyYAML

python3-pyyaml

pyyaml

yaml

python-ldap

python3-ldap

python-ldap

ldap, ldif, etc.

python-pillow

python3-pillow

pillow

PIL

python-jupyter-client

python3-jupyter-client

jupyter-client

jupyter_client

Donde sea este texto, las metavariables SRPMNAME, RPMNAME, PROJECTNAME, MODNAME refieren a estos nombres, respectivamente.

Nombre canónico del proyecto

La mayoría de estos nombres identificadores compatibles con máquinas que distinguen entre mayúsculas y minúsculas, pero el nombre del proyecto tiene una semántica amigable para el humano: no distingue entre mayúsculas y minúsculas y trata algunos conjuntos de caracteres (como ._-) especialmente. Para un uso automatizado, necesita ser normalizado a un formato canónico usado por las herramientas Python y los servicios como setuptools, pip y PyPI. Por ejemplo, el nombre canónico del proyecto Django es django (en minúsculas). Esta estandarización está definida en PEP 503, y la macro <<py_dist_name,the %{py_dist_name} la implementa para el empaquetamiento Fedora. El nombre canónico se obtiene cambiando el nombre del proyecto a minúsculas y convirtiendo todas las series de caracteres no alfanuméricos en caracteres simples“-”. Ejemplo: “The $$$ Tree” se convierte en “the-tree”.

En otra parte de este texto, la metavariable DISTNAME refiere al formulario canónico del nombre de proyecto.

Tenga en cuenta que, en algunos casos, se debe utilizar el nombre original del proyecto, sin normalizar. Por ejemplo, la macro «pypi_source,%pypi_source» y la macro %autosetup necesitan Django, no django.

Limitaciones del nombre

El carácter + en los nombres de los paquetes compilados (es decir, que no son SRPM) que incluyen los directorios .dist-info o .egg-info está reservado para Extras y NO DEBE utilizarse para ningún otro fin.

Como una excepción, los caracteres + PUEDEN aparecer al final de tales nombres.

El carácter + activa el generador automático de dependencias para los adicionales.

Reemplaza cualquier signo + en el nombre del upstream por -. Omite los signos «+» al principio del nombre. Considera la posibilidad de añadir Provides para el nombre original con los caracteres + para que los usuarios puedan encontrar el paquete más fácilmente.

Denominación de biblioteca

Un paquete integrado (es decir no SRPM) para una librería Python DEBE ser denominado con el prefijo python3-. Un paquete fuente que contiene principalmente una librería Python DEBE ser denominado con el prefijo python-.

El nombre del paquete Fedora CONTENDRÍA el «nombre canónico del proyecto». Si es posible, el nombre del proyecto SERÍA el mismo que el nombre del módulo importable principal, en minúsculas, con los guiones bajos (_) sustituidos por guiones (-).

Si el nombre del módulo importable y el nombre del proyecto no coinciden, los usuarios suelen acabar confundidos. En este caso, los empaquetadores ASEGURARÍAN que el desarrollador original sea consciente del problema y (especialmente en el caso de paquetes nuevos en los que sea posible cambiar el nombre) esforzarse por cambiar el nombre del paquete. El SIG de Python está disponible para ayudar.

Una biblioteca Python es un paquete destinado a ser importado en Python, como con import requests. Las herramientas como Ansible o IDLE, cuyo código es importable pero no está destinado principalmente a ser importado desde otro software, no se consideran bibliotecas en este sentido. Por lo tanto, esta sección no se aplica a ellas. (Consulte las directrices generales sobre bibliotecas y aplicaciones para obtener orientación general).

El nombre del componente Fedora (paquete fuente) para una biblioteca debe formarse tomando el nombre canónico del proyecto y anteponiéndole python- si aún no comienza con python-. Esto puede dar lugar a conflictos (por ejemplo, entre bugzilla y python-bugzilla). En ese caso, asegúrese de que el desarrollador original sea consciente de la posible confusión en la nomenclatura y aplique su mejor criterio.

Denominación de aplicación

Los paquetes que proporcionan principalmente aplicaciones, servicios o cualquier tipo de ejecutables DEBERÍAN nombrarse de acuerdo con las directrices generales Directrices de nomenclatura de Fedora (por ejemplo, ansible).

Considera añadir un proveedor virtual según lo indicado en «Nombres de bibliotecas» más arriba (por ejemplo, python3-PROJECTNAME), si ello ayuda a los usuarios a encontrar el paquete.

Archivos a incluir

Archivos fuente y caché de código byte

Los paquetes DEBEN incluir el archivo fuente (*.py) Y la caché de código byte (*.pyc) para cada módulo importable de Python puro. Los archivos fuente DEBEN incluirse en el mismo paquete que la caché de bytecode.

Los scripts que no se pueden importar (típicamente los que se encuentran en %{_bindir} o %{_libexecdir}) NO DEBEN compilarse en byte.

Los archivos de caché se encuentran en un directorio __pycache__ y tienen una extensión dependiente del intérprete, como .cpython-39.pyc.

La caché no es necesaria para ejecutar el software, pero si no se encuentra, Python intentará crearla cuando se importe un módulo. Si esto logran, el archivo no es rastreado por RPM y permanecerá en el sistema después de la desinstalación. Si no lo logran, los usuarios pueden obtener denegaciones AVC de SELinux espurias en las bitácoras.

Normalmente, la compilación de bytes (generación de los archivos de caché) la realiza el script brp-python-bytecompile BRP, que se ejecuta automáticamente después de que se haya procesado la sección %install del archivo de especificaciones. Compila en bytes cualquier archivo .py que encuentre en %{python3_sitelib} o %{python3_sitearch}.

Debe incluir estos archivos en su paquete (es decir, en la sección %files).

Si el código se encuentra en un subdirectorio (paquete importable), incluya todo el directorio:

%files
%{python3_sitelib}/foo/

Añadir la barra al final es una buena práctica para los directorios.

Sin embargo, esto no se puede utilizar para módulos de nivel superior (los que se encuentran directamente en, p.e. %{python3_sitelib}), ya que tanto %{python3_sitelib} como %{python3_sitelib}/__pycache__/ son propiedad del propio Python. En este caso, la macro %pycached puede ser de ayuda. Se expande al archivo fuente *.py dado y a sus archivos de caché correspondientes. Por ejemplo:

%files
%pycached %{python3_sitelib}/foo.py

se expande aproximadamente a:

%files
%{python3_sitelib}/foo.py
%{python3_sitelib}/__pycache__/foo.cpython-3X{,.opt-?}.pyc

Compilación de byte manual

Si necesitas compilar en bytes cosas fuera de %{python3_sitelib}/%{python3_sitearch}, emplee la %py_byte_compile.

Por ejemplo, si su software agrega %{_datadir}/mypackage a la ruta de importación de Python e importa el paquete foo desde allí, necesitará compilar foo con:

%py_byte_compile %{python3} %{buildroot}%{_datadir}/mypackage/foo/

Metadatos de información de distribución

Cada paquete de Python DEBE incluir Metadatos de Distribución de Paquete conformes con Especificaciones PyPA (especialmente, Registrando proyectos instalados).

Los metadatos SERÍAN incluidos en el mismo subpaquete como el módulo importable principal, si hay uno.

Esto aplica a bibliotecas (p.e. python-requests) así como herramientas (p.ej. ansible).

Cuando el software se desglose en varios subpaquetes, es CORRECTO para solo trasladar metadatos en una creación de RPM. En este caso, considere trabajar con desarrollo para además desglosar el proyecto en desarrollo.

Los metadatos toman la forma de un directorio .dist-info instalado en %{python3_sitelib} o %{python3_sitearch} y contienen información que herramientas como importlib.metadata utiliza para inspeccionar librerías instaladas.

Por ejemplo, un proyecto llamado MyLib con el paquete importable mylib podría ser empaquetado con:

%files -p python3-mylib
%{python3_sitelib}/mylib/
%{python3_sitelib}/MyLib-%{version}.dist-info/
%doc README.md
%license LICENSE.txt

Tenga en cuenta que algunas herramientas más antiguas en su lugar ponen los metadatos en un directorio .egg-info o incluso un único archivo. Esto no sucede si usted usa la macro %pyproject_wheel. Si su paquete usa un sistema de compilación que genera un directorio o archivo .egg-info, contacte, por favor, con Python SIG.

Como una excepción, la librería estándar Python PODRÍA distribuirse sin estos metadatos.

Listados explícitos

Los paquetes *NO DEBEN*poseer directorios compartidos propiedad del mismo Python, como los directorios de alto nivel __pycache__ (%{python3_sitelib}/__pycache__, %{python3_sitearch}/__pycache__).

De forma similar a la regla general, los empaquetadores NO DEBERÍAN simplemente usar comodines para todos lo que se encuentre bajo un directorio compartido.

Además de la lista general, NO DEBERÍA usarse lo siguiente en %files:

  • %{python3_sitelib}/*

  • %{python3_sitearch}/*

  • %{python_sitelib}/*

  • %{python_sitearch}/*

  • %pyproject_save_files '*'

  • %pyproject_save_files +auto

Esta regla sirve como comprobación de los errores comunes que por otro lado son difíciles de detectar. Esto limita algunas posibilidades de automatización.

Los errores más comunes que esta regla previene son:

  • instalando una suite de pruebas por todo el sistema como un módulo importable nombrado test, el cual entraría en conflicto entre otros sub‐paquetes, y

  • desarrollo añadiendo nuevos módulos importables inesperados; siempre comprobaría tales cambios para conflictos, y mantienen el listado de tales archivos explícitos y auditables.

Paridad PyPI

Cada paquete de Python en Fedora además ESTARÍA disponible en el Índice del Paquete Python (PyPI).

El comando pip install PROJECTNAME DEBE instalar el mismo paquete (posiblemente en una versión diferente), instala nada, o falla con un mensaje de error razonable.

Si esto no es el caso, el empaquetador CONTACTARÍA en desarrollo acerca de esto. El logro es obtener el nombre del proyecto registrado o bloqueado en PyPI, o por otra parte asegurar la regla es seguida.

Si su paquete no es o no puede ser publicado en PyPI, puede:

  • Pedir en desarrollo para publicarlo

  • Si desea: publicarlo para sí mismo en PyPI y gestionarlo

  • Pedir Python SIG para bloquear el nombre en PyPI por ti

  • Correo PyPI admins para bloquear el nombre por ti, proporcionando el nombre del proyecto y explicar la situación (por ejemplo: el paquete no puede ser instalado actualmente por medio de pip). Puede solicitar cuestiones y discutir el proceso en el Discurso de Python.

Los nombres de proyecto que estaban en Fedora pero no en PyPI cuado estas directrices fueron propuestas están bloquedados para ser subidos a PyPI. Esto impide que posibles trolls se apoderen de ellos, pero también bloquea a los propietarios legítimos. Si su paquete se ve afectado, contacte con el Python SIG o reporte un priblema PyPA y mencione @encukou.

Si el nombre de proyecto de su paquete entra en conflicto con un paquete diferente en PyPI, cambie el nombre del proyecto. Por muy doloroso que sea, necesitamos usar un único espacio de nombres en el ecosistema Python. El software que no está escrito específicamente para Fedora ya espera que los nombres de los proyectos usen el espacio de nombres PyPI: por ejemplo, si una librería de terceros identifica una dependencia por el nombre, no deseamos que esa dependencia sea satisfecha por un paquete Fedora no relacionado.

Como siempre, excepciones especificas pueden ser concedidas por el Comité de Empaquetados.

Proporciona y requerimientos

Proporciona para módulos importables

Para cualquier módulo destinado a ser utilizado en Python 3 con import MODNAME, el paquete que incluye PROPORCIONARÍA python3-MODNAME, con guiones bajos (_) sustituidos por guiones (-).

Esto, por suspuesto, ocurre siempre si el paquete se llama python3-MODNAME. Si el subpaquete tiene algún otro nombre, añada %py_provides python3-MODNAME explícitamente. Vea la siguiente sección para aprender sobre %py_provides.

Proporcionado automático por python- y python3.X-

Para cualquier FOO, un paquete que proporciona python3-FOO DEBERÍA usar %py_provides o un generador automático para también proporcionar python-FOO y python3.X-FOO, donde X es la versión menor del intérprete.

Los proporcionado NO DEBERÍA ser añadido manualmente: si no se usa un generador o una macro, no añada de ninguna manera python-FOO / python3.X-FOO.

Esto se hace automáticamente para los nombres de paquete por un generador. Si es absolutamente necesario, el generador puede ser deshabilitado indefiniendo the %__pythonname_provides macro.

Para lo proporcionado que no son nombres de paquete o (por razones técnicas) para paquetes sin archivos, el generador no trabajará. Para estos casos, se proporcionará la siguiente invocación python3-FOO, python-FOO y python3.X-FOO:

%py_provides python3-FOO

La utilización del generador o la macro es importante, porque la forma específica proporcionada puede cambiar en el futuro.

Proporcionados legibles por la máquina

Cada paquete Python DEBE proporcionar python3dist(DISTNAME) y python3.Xdist(DISTNAME), donde X es la versión menor del intérprete y DISTNAME es el Nombre canónico del proyecto correspondiente a los [Metadator de información de la distribución]. Por ejemplo, python3-django proporcionaría python3dist(django) y python3.9dist(django).

Esto se genera automáticamente desde los metadatos de información de distribución. Lo que proporciona NO DEBERÍA ser añadido manualmente: si el generador falla al añadirlo, se DEBE corregir los metadatos.

Estos Provides son usados automáticamente para Requires generados.

Si es absolutamente necesario, el generador automático puede ser deshabilitado quitando la definición de la %{?__pythondist_provides} macro. Considere debatir su caso de uso con el Python SIG si usted necesita hacer esto.

Dependencias

Como se menciona anteriormente, cada paquete Python DEBE explícitamente BuildRequire python3-devel.

Los paquetes NO DEBEN teneer dependencias (ni en tiempo de compilación ni de ejecución) con el prefijo sin versión python- si se puede usar la correspondiente dependencia python3- en su lugar.

Los paquetes NO DEBERÍAN tener dependencias explícitas (ni en tiempo de compilación ni de ejecución) con un prefijo de versión menor como python3.8- o python3.8dist(. Tales dependencias DEBERÍAN ser generadas automáticamente o se debería usar una macro para obtener la versión.

Los paquetes NO DEBERÍAN tener una dependencia explícita en tiempo de ejecución sobre python3.

En lugar de dependender de python3, los paquetes tienen una dependencia automática sobre python(abi) = 3.X cuando instalan archivos en %{python3_sitelib} o %{python3_sitearch}, o tiene una dependencia automática en /usr/bin/python3 si tienen scripts Python ejecutables o tienen una dependencia automática en libpython3.X.so.1.0() si incorporan Python.

Estas reglas ayudan a tener una actualización sin problemas cuando se actualiza python3 en nuevas versiones de Fedora.

Dependencias generadas automáticamente

Los paquetes DEBEN usar el generador automático Python de dependencia en tiempo de ejecución.

Los paquetes DEBERÍAN usar el generador opt-in build-dependency si es posible.

El empaquetador DEBE inspeccionar lo requerido generado para ver que es correcto. Todas las dependencias DEBEN ser resueltas dentro de la versión de Fedora objetivo.

Cualquier cambio necesario DEBE ser hecho mediante parches o modificando la fuente (por ejemplo. con sed), en lugar de deshabilitar el generador. El cambio resultante DEBERÍA ser ofrecido a desarrollador. Como excepción, el filtrado PODRÍA ser usado para soluciones temporales y arranque inicial.

Las dependencias cubiertas por los generadores NO DEBERÍAN ser repetidas en el archivo .spec. (Por ejemplo, si el generador encuentra una dependencia requests, Requires: python3-requests es redundante.)

Los requeridos generados automáticamente están en el formato python3.Xdist(DISTNAME), aumentados potencialmente con los requisitos de versión o combinados junto con dependencias ricas. Cualquier sufijo .0 es eliminado de los números de versión para coincidir con el comportamiento de las herramientas Python. (PEP 440 especifica que X.Y y X.Y.0 son tratados como iguales.)

Tenga en cuenta que los generadores solo cubren los paquetes Python. Otras dependencias, con frecuencia librerías C como openssl-devel, deben ser especificadas en el archivo .spec manualmente.

La forma en que se especifican los requisitos en el código fuente depende del sistema de compilación y de las preferencias de cada proyecto. Las ubicaciones comunes son pyproject.toml, setup.py, setup.cfg, config.toml.

Generador de dependencias en tiempo de ejecución

El generador automático de dependencias en tiempo de ejecución utiliza los metadatos del paquete (tal como se registra en los directorios instalados *.dist-info) para el paquete del que depende.

En caso de emergencia puede optar por no ejecutar el generador requerido por medio de añadiendo`%{?python_disable_dependency_generator} al paquete (normalmente, justo antes de la `%description principal del paquete).

Generador de dependencia en tiempo de creación

El generador de dependencia en tiempo de compilación opcional (pero altamente recomendado) recopila información de información del sistema de compilación pyproject.toml (con opción de reserva a setuptools) mas un gancho del sistema de compilación estandarizado para reunir más requisitos. Vea más detalles en la macro %pyproject_buildrequires macro.

Tenga en cuenta que sin el indicador -R, el generador incluirá los requisitos en tiempo de ejecución en BuildRequires. Esto es útil para ejecutar pruebas y para verificar que todas las dependencias están disponibles en Fedora.

Prueba de dependencias

Vea la sección [Tests].

Extras

Los extras de Python son una manera de que los proyectos Python requieren dependencias extras para funcionalidad adicional.

Por ejemplo, requests tiene varias dependencias estándar (por ejemplo`urllib3). Pero tambíen declara un extra denominado `requests[security], que enumera dependencias adicionales (por ejemplo, cryptography). A diferencia de los subpaquetes RPM, los extras pueden especificar solo dependencias adicionales, no archivos adicionales. El paquete principal funcionará si la dependencia opcional no está instalada, pero podría tener la funcionalidad limitada.

Las herramientas Python tratan los extras como paquetes virtuales. Por ejemplo, si un usuario ejecuta pip install 'requests[security]' o instala un proyecto que depende de requests[security], serán instalados requests y cryptography.

En Fedora, los extras son proporcionados normalmente por paquetes sin archivos. En lugar de corchetes, los nombres de paquetes Fedora usan convencionalmente el carácter + (que es válido en los nombres de paquete RPM, pero no en los nombres canónicos de proyectos Python ni en los identificadores de extras).

Manipulando adicionales

Los paquetes Python TENDRÍAN Provides para todos los adicionales del proyecto en desarrollo especificados, excepto:

  • aquellos que no son útiles para otros paquetes (por ejemplo requisitos de build/desarrollo, comunmente nombrados dev, doc o test), y

  • aquellos que tienen requisitos que no están empaquetados en Fedora.

Un paquete que proporciona un extra Python DEBE proporcionar python3dist(DISTNAME[EXTRA]) y python3.Xdist(DISTNAME[EXTRA]), donde X es la versión menor del intérprete, DISTNAME es el [Canonical project name] (Nombre canónico del proyecto) y EXTRA es el nombre de un simple extra. Por ejemplo, python3.9dist(requests[security]). Estos requisitos DEBERÍAN ser generados usando el generador automático de dependencias.

Un paquete que proporcionar un Python adicional DEBE requerir el paquete principal de extras con exacto NEVR.

Un subpaquete que primariamente proporciona un adicional de Python SERÍA nombrado por apéndice + y el nombre adicional para el nombre del paquete adicional. Por ejemplo, python3-requests+security.

The most straightforward way to provide an extra is with a dedicated subpackage containing no files (a “metapackage”). This case can be automated with the %pyproject_extras_subpkg macro or the %python_extras_subpkg macro.

This is not the only way: when some extra is always useful in a distro, it can be provided by the main package; when several extras are related, they may be provided by a single subpackage. However, having one dedicated subpackage per extra allows you to use the automatic dependency generator to ensure that the extras’ requirements will stay in sync with upstream. If you create a dedicated subpackage and want it to be always/usually installed, you can Require/Recommend/Suggest it from the main package.

El generador de dependencia para actividades adicionales si el siguiente mantiene:

  • El nombre del paquete debe terminar con +EXTRA (donde EXTRA está en el nombre adicional).

  • El paquete debe contiene el directorio .dist-info , usualmente como %ghost.

Ejemplo y mocos convenientes

El subpaquete adicional para setuptools_scm[toml] puede ser especificado utilizando la conveniente macro %pyproject_extras_subpkg como sigue. La macro toma el nombre del paquete principal y los nombre(s) del adicional(es):

%pyproject_extras_subpkg -n python3-setuptools_scm toml

Si no utiliza %pyproject_install, en su lugar necesitará el usuario %python_extras_subpkg y aprobar una ruta para el directorio dist-info:

%python_extras_subpkg -n python3-setuptools_scm -i %{python3_sitelib}/*.dist-info toml

For this case, the extras dependency generator will read upstream metadata from the .dist-info directory. If it finds that the extra requires on toml, it will generate Requires: python3.Xdist(toml) and Provides: python3dist(setuptools-scm[toml]) (and the corresponding python3.Xdist provide).

If you need additional features that the *_extras_subpkg macros do not cover, you will need to write the subpackage sections manually. Such features can be, for example:

  • Obsoleting/providing other names (e.g. obsoleted extras packages)

  • Manual strong or weak dependencies on other (possibly non-Python) packages

As an example of what you need to write in these cases, both of the *_extras_subpkg macro invocations above expand to the following:

%package -n python3-setuptools_scm+toml
Summary: Metapackage for python3-setuptools_scm: toml extra
Requires: python3-setuptools_scm = %{?epoch:%{epoch}:}%{version}-%{release}

%description -n python3-setuptools_scm+toml
This is a metapackage bringing in toml extra requires for python3-setuptools_scm.
It contains no code, just makes sure the dependencies are installed.

%files -n python3-setuptools_scm+toml
%ghost %{python3_sitelib}/*.dist-info

Note that the dependency generator does not add a dependency on the main package (the Requires: python3-setuptools_scm = ... above). If you are not using the %python_extras_subpkg macro, you need to add it manually.

Removing extras

If an existing extra is removed from an upstream project, the Fedora maintainer SHOULD try to convince upstream to re-introduce it (with an empty list of dependencies). If that fails, the extra SHOULD be Obsoleted from either the main package or another extras subpackage.

Note that removing extras is discouraged in setuptools documentation (see the Tip box near the end of the Optional dependencies section).

Automatic Requires for extras

The automatic [Run-time dependency generator] will generate Requires on python3.Xdist(DISTNAME[EXTRA]) from upstream Requires-Dist metadata.

If the required package does not yet provide metadata for the extra, contact the Fedora maintainer to add it.

In an emergency, you can define the %_python_no_extras_requires macro to avoid automatically generating all extras requirements.

Interpreter invocation

Travesuras

Líneas Shebang para invocar Python DEBE utilizar %{python3} como el interpretador.

Shebang lines to invoke Python SHOULD be #!%{python3} -%{py3_shebang_flags} and they MAY include extra flags.

Si (algunos) de los indicadores por defecto desde la macro %{py3_shebang_flags} no es deseable, los paquetes explícitamente REDEFINIRÍA la macro para retirarlas por desdefinir la macro %{_py3_shebang_...} relevante.

Using #!%{python3} (#!/usr/bin/python3) rather than e.g. #!/usr/bin/env python ensures that the system-wide Python interpreter is used to run the code, even if the user modifies $PATH (e.g. by activating a virtual environment).

Por defecto, -%{py3_shebang_flags} expande a -sP (o sólo -s en la versión de Python más baja que 3.11 y Fedora Linux más antiguo que 37).

The -s flag, stored in the %{_py3_shebang_s} macro, means don’t add user site directory to sys.path. That ensures the user’s Python packages (e.g. installed by pip install --user, or just placed in the current directory) don’t interfere with the RPM installed software. Sometimes, such content is desirable, such as with plugins.

The -P flag, stored in the %{_py3_shebang_P} macro, means don’t add the script’s directory to sys.path. Sometimes, adding the script’s directory to sys.path is desirable, such as with executable Python scripts installed in a custom directory, importing each other.

Removing the undesired flag(s) from the %{py3_shebang_flags} macro rather than not using the macro at all, ensures that existing or future automation won’t add the flag.

# Remove -s from Python shebang - ensure that extensions installed with pip
# to user locations are seen and properly loaded
%undefine _py3_shebang_s
# Don't add -P to Python shebangs
# The executable Python scripts in /usr/share/opt-viewer/ import each other
%undefine _py3_shebang_P

The %pyproject_install macro automatically changes all Python shebangs in %{buildroot}%{_bindir}/* to use %{python3} and add contents of the %{py3_shebang_flags} macro to the existing flags. If you’re not using that macro or you need to change a shebang in a different directory, you can use the %py3_shebang_fix macro as follows:

%py3_shebang_fix SCRIPTNAME …

Invokable Python modules

Every executable TOOL for which the current version of Python matters SHOULD also be invokable by python3 -m TOOL.

If the software doesn’t provide this functionality, packagers SHOULD ask the upstream to add it.

This applies to tools that modify the current Python environment (like installing or querying packages), use Python for configuration, or use Python to run plugins. It does not apply to tools like GIMP or Bash which support plugins in multiple languages and/or have other means to specify the interpreter.

For example, pip can be invoked as python3 -m pip.

This allows users to accurately specify the Python version used to run the software. This convention works across different environments that might not always set $PATH or install scripts consistently.

Using Cython

Tightening the general Fedora policy, packages MUST NOT use files pre-generated by Cython. These MUST be deleted in %prep and regenerated during the build.

As an exception, these sources MAY be used temporarily to prevent build time circular dependencies by following the bootstrapping guidelines.

Generated files (the ones that must be deleted) have a generic .c or .cpp extension. Cython source files (which should stay) usually have the .pyx or .pxd extension.

Cython is a popular tool for writing extension modules for Python. If compiles a Python-like language to C, which is then fed to the C compiler. Historically, Cython was hard to use upstream as a build-time dependency. Many projects include pre-generated C files in source distributions to avoid users from needing to install the tool.

Cython uses CPython’s fast-changing internal API for performance reasons. For a new release of Python, Cython generally needs to be updated and the C files regenerated. In Fedora, this is frequently needed before upstreams release re-generated sources (e.g. for Alpha versins of Python). Since we do not have a problem with build-time dependencies, we always want to run the Cython step.

For example, PyYAML removes a generated C file with:

rm -rf ext/_yaml.c

For another example, in python-lxml all C files are generated with Cython, which allows removing them with:

# Remove pregenerated Cython C sources
find -type f -name '*.c' -print -delete

Some upstreams mix generated and hand-written C files. In such cases a grep like this one from scipy helps (but might not be entirely future proof):

# Remove pregenerated Cython C sources
rm $(grep -rl '/\* Generated by Cython')

Pruebas

Ejecutar pruebas

If a test suite exists upstream, it SHOULD be run in the %check section. If that is not possible with reasonable effort, at least a basic smoke test (such as importing the packaged module) MUST be run in %check.

You MAY exclude specific failing tests. You MUST NOT disable the entire testsuite or ignore its result to solve a build failure.

As an exception, you MAY disable tests with an appropriate %if conditional (e.g. bcond) when bootstrapping.

Most errors in Python happen at run-time, so tests are extremely important to root out issues, especially when mass rebuilds are required.

Common reasons for skipping tests in %check include requiring network access, dependencies not packaged in Fedora, and/or specialized hardware or resources.

In these cases, you can use the %pyproject_check_import or the %py3_check_import macro to test that installed modules are importable.

Tox

A popular testing tool, and one which is well integrated in Fedora, is tox. Upstream, it is commonly used to test against multiple Python versions. In a Fedora package, BuildRequire test dependencies via %pyproject_buildrequires -t or -e (see Test dependencies below) and run tox with:

%tox

This sets up the environment ($PATH, $PYTHONPATH, $TOX_TESTENV_PASSENV) and instructs tox to use the current environment rather than create new ones. For more options, see Build macros.

pytest

When upstream doesn’t use tox, the tests need to be run directly depending on upstream choice of a test runner. A popular runner is pytest, which can be invoked using %pytest.

Use positional arguments to specify the test directory. See python3 -m pytest --help for how to select tests. For example, if network-related tests are marked “network”, you might use -m to deselect them:

%pytest -m "not network"

The %pytest macro sets several environment variables appropriate for %check:

  • Locations in the buildroot are added to $PATH and $PYTHONPATH.

  • $PYTHONDONTWRITEBYTECODE is set to avoid writing pytest-specific cache files to buildroot

  • $PYTEST_XDIST_AUTO_NUM_WORKERS is set to %{_smp_build_ncpus}

  • If unset, $CFLAGS and $LDFLAGS are set to match the build flags

Other test runners

If upstream doesn’t use tox or pytest, other test runners can be invoked with the %{py3_test_envvars} macro, available since Fedora Linux 38.

This macro sets several environment variables similarly to %pytest, but requires the actual test runner to be invoked after the macro, for example:

%{py3_test_envvars} %{python3} -m unittest

Or:

%{py3_test_envvars} %{python3} tests/run_tests.py

Prueba de dependencias

One part of the Python packaging ecosystem that is still not standardized is specifying test dependencies (and development dependencies in general).

A good, common way for upstreams to specify test dependencies is using an extra like [test], [testing] or [dev]. In this case, upstream’s instructions to install test dependencies might look like $ pip install -e.[test].

Another way to specify test dependencies is using a dedicated dependency group (PEP 735).

Projects using tox usually specify test dependencies in a tox-specific format: a requires key in the configuration.

These three forms are handled by the %pyproject_buildrequires macro.

If upstream does not use either form, list test dependencies as manual BuildRequires in the spec file, for example:

# Test dependencies:
BuildRequires: python3dist(pytest)

If you need to do this, consider asking upstream to add a [test] extra or a test dependency group.

Linters

In %check, packages SHOULD NOT run “linters”: code style checkers, test coverage checkers and other tools that check code quality rather than functionality.

Tools like black, pylint, flake8, or mypy are often “opinionated” and their “opinions” change frequently enough that they are nuisance in Fedora, where the linter is not pinned to an exact version. Furthermore, some of these tools take a long time to adapt to new Python versions, preventing early testing with Alpha and Beta releases of Python. And they are just not needed: wrongly formatted code is not important enough for the Fedora packager to bug the upstream about it. Making such an issue break a package build is entirely unreasonable.

Linters do make sense in upstream CI. But not in Fedora.

If a linter is used, disable it and remove the dependency on it. If that is not easy, talk to upstream about making it easy (for example with a configuration option or a separate tox environment).

For packages that contain such linters, use them at runtime or extend them, you will usually need to run the linter in %check. Run it to test functionality, not code quality of the packaged software.

Source files from PyPI

Packages MAY use sources from PyPI.

However, packages SHOULD NOT use an archive that omits test suites, licenses and/or documentation present in other source archives.

For example, as of this writing pip provides a source tarball (“sdist”) which omits the relatively large tests and docs directories present in the source on GitHub. In this case, the tarball from GitHub should be used. (See the Git tags section of Fedora SourceURL guidelines.)

When using sources from PyPI, you can use the the %pypi_source macro to generate the proper URL.

Some Python packages use metadata from git (or a similar version control system) to construct their version string, for example via setuptools_scm. When publishing a package to PyPI, this version metadata is usually stored and included in a file, so the version control history is no longer needed to construct it. However, when using tarballs from a git forge directly, this version information is missing and must be manually provided by the packager. For example, the SETUPTOOLS_SCM_PRETEND_VERSION environment variable can be set to the desired value in the %generate_buildrequires and %build scripts in the spec file for packages that use setuptools_scm for this purpose.

Example spec file

The following is a viable spec file for a Python library called Pello that follows packaging best practices.

Note that the project name Pello normalizes to the lowercase pello. The example spec shows where each variant is typically used.

The project has an extra color, which enables colorized output when installed. Since the required dependency is quite minimal and color improves the user experience, the extra is Recommended from the main package.

Name:           python-pello
Version:        1.0.4
Release:        1%{?dist}
Summary:        Example Python library

License:        MIT-0
URL:            https://github.com/fedora-python/Pello
Source:         %{url}/archive/v%{version}/Pello-%{version}.tar.gz

BuildArch:      noarch
BuildRequires:  python3-devel

%global _description %{expand:
A python module which provides a convenient example.
This description provides some details.}

%description %_description

%package -n python3-pello
Summary:        %{summary}
Recommends:     python3-pello+color

%description -n python3-pello %_description


%pyproject_extras_subpkg -n python3-pello color

%prep
%autosetup -p1 -n Pello-%{version}


%generate_buildrequires
%pyproject_buildrequires -t


%build
%pyproject_wheel


%install
%pyproject_install

# Here, "pello" is the name of the importable module.
%pyproject_save_files -l pello


%check
%tox


# Note that there is no %%files section for
# the unversioned python module, python-pello.

# For python3-pello, %%{pyproject_files} handles code files and %%license,
# but executables and documentation must be listed in the spec file:

%files -n python3-pello -f %{pyproject_files}
%doc README.md
%{_bindir}/pello_greeting


%changelog

Empty spec file

The following is an unfinished spec file template to copy, paste and edit.

Name:           python-...
Version:        ...
Release:        0%{?dist}
Summary:        ...

License:        ...
URL:            https://...
Source:         %{url}/archive/v%{version}/...-%{version}.tar.gz / %{pypi_source ...}

BuildArch:      noarch / BuildRequires:  gcc
BuildRequires:  python3-devel

%global _description %{expand:
...}

%description %_description

%package -n python3-...
Summary:        %{summary}

%description -n python3-... %_description


%prep
%autosetup -p1 -n ...-%{version}


%generate_buildrequires
%pyproject_buildrequires -x... / -g... / -t


%build
%pyproject_wheel


%install
%pyproject_install
%pyproject_save_files ...


%check
%tox / %pytest / %pyproject_check_import ...


%files -n python3-... -f %{pyproject_files}
%doc README.*
%{_bindir}/...


%changelog

Macro Reference

This section documents macros that are available to help with Python packaging. The expansions in parentheses are provided only as reference/examples.

See the [Mandatory macros] section above for:

  • %{python3} (/usr/bin/python3)

  • %{python3_version} (e.g. 3.9)

  • %{python3_version_nodots} (e.g. 39)

  • %{python3_sitelib} (e.g. /usr/lib/python3.9/site-packages)

  • %{python3_sitearch} (e.g. /usr/lib64/python3.9/site-packages)

Shebang macros

  • %{py3_shebang_flags} (sP or s before Fedora Linux 37)

    Flags for %{python3} to use in shebangs. See [Shebangs] for details. Includes flags from several %{_py3_shebang_...} macros listed here.

  • %{_py3_shebang_s} (s)

    Undefine this macro to drop s from %{py3_shebang_flags}.

  • %{_py3_shebang_P} (P)

    Undefine this macro to drop P from %{py3_shebang_flags}. Introduced in Fedora Linux 37.

  • %py3_shebang_fix PATHS (pathfix.py ... PATHS)

    A macro to fix shebangs in specified PATHS. Only shebangs that already have python in them are changed. If a directory is given, all .py files in it are fixed, recursively. (So, if you need to fix shebangs in files not named *.py, you need to list each file separately or use a Shell glob, such as %{buildroot}%{_libexecdir}/mytool/*.) Existing flags are preserved and %{py3_shebang_flags} are added.

    For example, #! /usr/bin/env python will be changed to #! /usr/bin/python3 -s and #! /usr/bin/python -u will be changed to #! /usr/bin/python3 -su.

    This macro is called automatically by %pyproject_install on %{buildroot}%{_bindir}/*.

Convenience macros

  • %{pypi_source PROJECTNAME [VERSION [EXT]]} (e.g. https://.../Django-3.0.5.tar.gz)

    Evaluates to the appropriate URL for source archive hosted on PyPI. Accepts the project name and up to two optional arguments:

    • La versión del proyecto PyPI. Por defecto en la versión %version (la versión de paquete) con cualquier ~ retirado.

    • La extensión del archivo para utilizar. Por defecto a tar.gz.

    In most cases it is not necessary to specify those two arguments.

    Para retro-compatibilidad, el primer argumento es técnicamente opcional también, pero omitirlo está obsoleto. (Por defecto a %srcname si está definido, o para %pypi_name si está definido, o para %name.)

  • %{python3_platform} (e.g. linux-x86_64)

    The platform name. Used in some Python build systems. This corresponds to sysconfig.get_platform().

  • %{python3_ext_suffix} (e.g. .cpython-39-x86_64-linux-gnu.so)

    Filename extension for Python extension modules. This corresponds to the EXT_SUFFIX sysconfig variable.

  • %{python3_platform_triplet} (e.g. x86_64-linux-gnu)

    A string identifying the architecture/platform. This corresponds to the MULTIARCH sysconfig variable.

  • %{python3_cache_tag} (e.g. cpython-311)

    Part of the bytecode cache filename that identifies the interpreter. This corresponds to the sys.implementation.cache_tag value.

Build macros

The “pyproject macros” are most useful for packaging Python projects that use the pyproject.toml file defined in PEP 518 and PEP 517, which specifies the package’s build dependencies (including the build system, such as setuptools, flit or poetry).

If pyproject.toml is not found, the macros automatically fall backs to using setuptools with configuration in setup.cfg/setup.py.

A full tutorial and discussion for the macros is available in the macros’ README.

  • %pyproject_buildrequires

    Generate BuildRequires for the package. Used in the %generate_buildrequires section of the spec file. The macro has these options:

    • -R: Don’t include run-time requirements (e.g. if the build backend does not support this).

    • -r: Incluye requisitos en tiempo de ejecución (este indicador no es necesario y existe por razones de compatibilidad hacia atrás exclusivamente, los requerimientos en tiempo de ejecución se incluyen por defecto.

    • -x EXTRA: Include dependencies given by the given extra. Cannot be used with -R.

    • -g GROUP: Include dependencies specified in the given dependency group (PEP 735).

    • -p: Read run-time dependencies from pyproject.toml [project] table. This reads also the [optional-dependencies] for the given extra. Cannot be used with -R.

    • -t: Incluye dependencias para el entorno tox por defecto. No puede ser utilizado con -R.

    • -e ENV: Include dependencies for the given tox environment, and save the ENV name as %{toxenv}. Cannot be used with -R. Multiple comma separated values can be given, for example:

      %pyproject_buildrequires -e %{toxenv}-unit,%{toxenv}-integration
    • Additional arguments are treated as paths to requirements.txt that are added on top of these dependencies

  • %pyproject_wheel

    Build the package. Commonly, this is the only macro needed in the %build section.

    This macro needs BuildRequires generated by %pyproject_buildrequires.

  • %pyproject_install

    Install the package built by %pyproject_wheel. Calls %py3_shebang_fix %{_buildroot}%{_bindir}/*.

    This macro needs BuildRequires generated by %pyproject_buildrequires.

  • %pyproject_save_files MODNAME …

    Generate a list of files corresponding to the given importable module(s) and save it as %{pyproject_files}.

    Note that README file is not included. The LICENSE file is included when it is specified in the metadata. Also, while the macro allows including executable and other files (using the +auto flag), this feature MUST NOT be used in Fedora.

    The MODNAME may be a glob pattern, which should be specific to your package. To prevent Shell from expanding the globs, put them in '', e.g. %pyproject_save_files '*pytest'. As mentioned in the [Explicit lists] section, expressions like %pyproject_save_files '*' are not acceptable.

    The macro has these options:

    • -l: Declare that a missing license should terminate the build. Packagers are encouraged to use this flag when the %license file is not manually listed in %files to avoid accidentally losing the file in a future version.

    • -L: Explicitly disable the check for a missing license file. When the %license file is manually listed in %files, packagers can use this flag to ensure future compatibility in case the -l behavior eventually becomes a default.

    • -M: Do not list any modules. When the package has no Python modules in it or when you need to list the modules in %files manually, this option allows to save just the non-module files (such as the .dist-info metadata directory). This option cannot be combined with `MODNAME`s.

  • %{pyproject_files}

    Path of the file written by %pyproject_save_files, to be used as:

    %files -n python3-DISTNAME -f %{pyproject_files}

Test macros

  • %tox

    Run tests using tox.

    This macro needs BuildRequires generated by the -t or -e option of the %pyproject_buildrequires macro.

    Different environments may be specified with -e, for example:

    %check
    %tox %{?with_integration_tests:-e %{toxenv},%{toxenv}-integration}

    Flags for the tox command can be specified after --:

     %tox -- --parallel 0

    Additional arguments for the test runner may be specified after another --:

     %tox -- --parallel 0 -- --verbose tests/*
  • %{toxenv}

    The tox environment(s) used by the %tox macro. Multiple environments are separated by commas. Can be overridden manually or with %pyproject_buildrequires -t ENV1,ENV2.

  • %{default_toxenv} (p.ej., py39)

    Por defecto el valor de todo el sistema de %{toxenv}.

  • %pytest

    Run %__pytest with environment variables appropriate for tests in %check. See [Running tests] for details.

  • %__pytest (/usr/bin/pytest)

    The command that %pytest uses. May be redefined.

  • %py3_test_envvars (PATH=... PYTHONPATH=... PYTHONDONTWRITEBYTECODE=1 ...)

    The environment variables used by %pytest and %tox. It may be used to invoke custom test runners in %check. See Other test runners for details. Introduced in Fedora Linux 38.

  • %py3_check_import

    Imports all provided modules. If running an upstream test suite is not feasible, use this macro in %check to test that public Python modules are importable.

    Takes these arguments:

    • -f: path to file containing qualified module names (separated by newlines). Optional, can be used multiple times.

    • -e: glob to exclude the matching module names. Optional, can be used multiple times.

    • -t: if set, import only top-level module names

    • Positional arguments (separated by spaces or commas) specify the module name(s) to check.

    The macro sets various environment variables such as PATH and PYTHONPATH to ensure the packaged versions of modules are imported.

  • %pyproject_check_import

    Imports all public modules found by the %pyproject_save_files macro whose names match any of the provided MODNAME globs.

    This macro needs to be used with %pyproject_save_files (use %py3_check_import in other cases).

    The macro takes -e/-t as well as positional arguments for %py3_check_import above.

Extras macros

  • %pyproject_extras_subpkg

    Generates a simple subpackage for a Python extra. See Extras for more information.

    This macro needs to be used with %pyproject_install (use %python_extras_subpkg in other cases).

    Argumentos requeridos:

    • -n: name of the “base” package (e.g. python3-requests)

    • Positional arguments (separated by spaces or commas): the extra name(s). Multiple metapackages are generated when multiple names are provided.

    The macro also takes -i/-f/-F arguments for %python_extras_subpkg below, but if they are not given, a filelist written by %pyproject_install is used.

    Similarly, the -a/-A flags are passed to %python_extras_subpkg.

    Este macro genera todas las secciones de definición del subpaquete (%package incluyendo el Summary y Requires en el paquete base, %description y, por defecto, %files). De ahí, no puede ser extendido con personalización Provides/Obsoletes/Requires/etc. Esta macro está diseñado para que quepa soloo en los usos más comunes. Para utilizaciones más complicadas, construye el subpaquete manualmente como muestra en la sección Extras.

    The %files section is last. It can be continued to add files that only make sense with the extra and the base package does not fail without them. For example, the following macro will package the extra cli for the project a-cool-tool and include an a-cool-tool command:

    %pyproject_extras_subpkg -n a-cool-tool cli
    %{_bindir}/a-cool-tool

    Due to technical limitations, the macro never generates requirements on the arched BASE_PACKAGE%{?_isa} = %{?epoch:%{epoch}:}%{version}-%{release}. It only adds Requires: BASE_PACKAGE = %{?epoch:%{epoch}:}%{version}-%{release}) because a macro cannot reliably detect if the subpackage is arched or not. So far, this has not been a problem in practice.

  • %python_extras_subpkg

    Generates a simple subpackage for a Python extra. See Extras for more information. Takes these arguments:

    • -n: name of the “base” package (e.g. python3-requests)

    • -i: the %files %ghost path (glob) to the .dist-info directory

    • Positional arguments (separated by spaces or commas) specify the extra name(s) — multiple metapackages are generated when multiple names are provided.

    • -f: Relative path to the filelist for this metapackage (which should contain the %files %ghost path (glob) to the the metadata directory). Conflicts with -i and -F.

    • -F: Skip the %files section entirely (if the packager wants to construct it manually). Conflicts with -i and -f.

    • -a: Include BuildArch: noarch in the package definition, to be used only when the package is archful, but the “base” package passed to -n is not.

    • -A: Explicitly disables -a (does nothing at the moment).

    As with %pyproject_extras_subpkg:

    • This macro generates all the subpackage definition sections, with only %files being customizable. For more complicated uses, construct the subpackage manually as shown in the Extras section.

    • It never generates requirements on the arched BASE_PACKAGE%{?_isa} = %{?epoch:%{epoch}:}%{version}-%{release}.

Manual generation

The following macros are available for cases where automatic generation is turned off. They can also be useful for handling files in non-standard locations where the generators don’t look.

  • %pycached MODNAME.py

    Given a Python file, lists the file and the files with its bytecode cache. See Source files and bytecode cache for more information.

  • %py_byte_compile INTERPRETER PATH

    Byte-compile a Python file into a __pycache__/*.pyc.

    If the PATH argument is a directory, the macro will recursively byte compile all *.py files in the directory. (So, if you need to compile files not named *.py, you need to use the macro on each file separately.)

    El INTERPRETER determina el sufijo del nombre de archivo compilado y el número mágico embebido en el archivo. Estos muct coinciden con el intérprete que importará el archivo. Normalmente, el INTERPRETER sería establecido a %{python3}. Si estás compilando para un intérprete no por defecto, utilice ese intérprete en su lugar y añada una línea BuildRequires para ello.

  • %{py_dist_name PROJECTNAME}

    Given a project name (e.g. PyYAML) it will convert it to the canonical format (e.g. pyyaml). See [Canonical project name] for more information.

  • %{py3_dist PROJECTNAME …}

    Given one or more project names, it will convert them to the canonical format and evaluate to python3dist(DISTNAME), which is useful when listing dependencies. See Proporcionados legibles por la máquina for more information.

Ajustes del sistema

The following macros can be redefined for special use cases.

  • %{__python} (errores por defecto si no redefinidos)

    Defining this macro sets the meaning of all “unversioned” Python macros such as %{python} or %{python_sitelib}. Don’t use these macros without redefining %{__python}.

  • %{__python3} (/usr/bin/python3)

    The python 3 interpreter. Redefining this macro changes all the %{python3...} macros, e.g. %{python3} or %{python3_sitelib}.

  • %{python3_pkgversion} (3)

    Distro-wide Python version, i.e. the 3 in python3. Projects that build on top of Fedora might define it to e.g. 3.9 to try allowing multiple Python stacks installable in parallel. Packages in Fedora MAY use it (e.g. in package names: python%{python3_pkgversion}-requests), but MUST NOT redefine it.

Comparing Python versions

When comparing Python versions (e.g. to ask: is %{python3_version} greater than 3.8?), using naïve %if %{python3_version} > 3.8 or %if "%{python3_version}" > "3.8" is not possible, because the comparison is performed alphabetically on strings. Hence it is true that "3.10" < "3.8" (which is not desired).

It is possible to explicitly compare version literals by using the v prefix, similar to the Python string prefixes:

%if v"0%{?python3_version}" > v"3.8"
...
%endif

As a workaround for compatibility with RPM releases up to 4.16 (EPEL 9), %{python3_version_nodots} can be compared as an integers:

%if 0%{?python3_version_nodots} > 39
...
%endif

This will work with Python 3.10 (310 > 39), but eventually break with Python 4.0 (40 < 310).

Disabling automation

The following macros can turn off Python-specific automation.

Consider contacting the Python SIG if you need to do this.

Deprecated Macros

The following macros are deprecated. See the 201x-era Python Packaging guidelines for how some of them were used.

  • %py3_build

  • %py3_build_wheel

  • %py3_build_egg

  • %py3_install

  • %py3_install_wheel

  • %py3_install_egg

  • %py3dir

  • %py3_other_build

  • %py3_other_install

  • %python_provide