Global y nonlocal en Python

Guía clara sobre global y nonlocal en Python: diferencias, ejemplos y buenas prácticas para evitar UnboundLocalError en código de proyectos a medida.

19 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Global vs nonlocal en Python: explicación clara y ejemplos prácticos

En Python existen dos declaraciones que permiten a funciones internas acceder o modificar variables definidas fuera de su ámbito local: global y nonlocal. Entender la diferencia es clave para evitar errores como UnboundLocalError y para diseñar código limpio en proyectos de aplicaciones a medida y software a medida.

Uso de global: la declaración global indica que una variable referenciada dentro de una función remite a la variable global del módulo. Ejemplo simplificado en una sola línea para ilustrar la idea: num = 2; def first(): num = 4; def second(): num = 6; def third(): global num; print(num) # imprime 2. Si además se modifica la variable con global num; num += 10; print(num) entonces la variable global se actualiza y pasa a valer 12.

Uso de nonlocal: nonlocal se emplea en funciones anidadas para referirse a una variable definida en la función exterior inmediata, no en el ámbito global. Ejemplo compacto: num = 2; def first(): num = 4; def second(): num = 6; def third(): nonlocal num; print(num) # imprime 6. Si en third se hace nonlocal num; num += 10; print(num) entonces la variable del ámbito exterior inmediato se modifica y pasa a valer 16 dentro de ese contexto.

Diferencia clave: global apunta al ámbito del módulo, nonlocal apunta al ámbito de una función exterior inmediata. Sin declarar nonlocal o global, una función interior puede leer variables de ámbitos exteriores, pero si intenta asignarles o incrementarlas sin la declaración adecuada Python asume que son locales y se produce UnboundLocalError al intentar usar la variable antes de inicializarla. Ejemplo reducido: intentar hacer num += 5 dentro de una función interior sin declarar nonlocal provoca UnboundLocalError.

No mezclar global y nonlocal en la misma función: Python prohíbe declarar una misma variable como nonlocal y global en la misma función anidada y lanzará un error de sintaxis. Diseñar el alcance de las variables con claridad evita este tipo de conflictos.

Buenas prácticas: evitar abusar de variables globales; preferir pasar parámetros, devolver resultados, usar objetos y atributos de clase o emplear closures con nonlocal cuando convenga. Para proyectos profesionales de software a medida y aplicaciones a medida estas prácticas facilitan mantenibilidad, pruebas y escalabilidad, especialmente cuando se integran soluciones de inteligencia artificial o agentes IA.

Cómo podemos ayudarte desde Q2BSTUDIO: en Q2BSTUDIO somos una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida. Ofrecemos integración de inteligencia artificial y soluciones de ia para empresas, implementación de agentes IA, consultoría en ciberseguridad, servicios cloud aws y azure y servicios de inteligencia de negocio incluyendo power bi para visualización y análisis. Nuestros equipos ayudan a definir la arquitectura correcta, aplicar buenas prácticas de programación y evitar problemas de alcance de variables al diseñar sistemas complejos con componentes de IA, pipelines de datos y microservicios.

Servicios destacados de Q2BSTUDIO: aplicaciones a medida, desarrollo de software a medida, proyectos de inteligencia artificial, agentes IA personalizados, consultoría en ciberseguridad, migración y gestión en servicios cloud aws y azure, servicios inteligencia de negocio y dashboards con power bi. Combinamos experiencia técnica con prácticas de seguridad y escalabilidad para que tu proyecto funcione en producción.

Si necesitas ayuda para diseñar código fiable que integre inteligencia artificial, agentes IA o soluciones en la nube, contacta con Q2BSTUDIO y te acompañamos desde el prototipo hasta la entrega en producción con enfoque en ciberseguridad y rendimiento.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat