Alcance global frente a nonlocal en Python 3

Guía de alcance de variables en Python: global, nonlocal, local y clase, con ejemplos y errores comunes. Buenas prácticas y servicios de software a medida e IA de Q2BSTUDIO.

20 ago 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En Python las variables pueden entenderse desde cuatro perspectivas según la posicion relativa a una funcion anidada como third: variable global, variable no local, variable local y variable de clase. Una variable global vive en el nivel del modulo fuera de cualquier funcion o clase. Una variable no local se encuentra en una funcion exterior al ambito actual. Una variable local pertenece al cuerpo de la funcion que la define. Una variable de clase es un nombre definido dentro del bloque de una clase.

La instruccion global permite indicar que un nombre dentro de una funcion debe enlazarse al nombre del modulo. Al usar global num dentro de third el interprete busca num en el ambito global. Si existe un num en el nivel de modulo third puede leerlo y modificarlo. Si no existe y se intenta leer num se produce NameError. Si se declara global y luego se hace una asignacion como num += 10 se modifica el valor global visible desde cualquier otra funcion y desde el codigo del modulo.

La instruccion nonlocal permite enlazar un nombre al ambito de la funcion mas cercana que lo define, es decir al primer ambito envolvente que no sea el global. Nonlocal no puede referirse a nombres de clase ni a nombres globales. Si third declara nonlocal num y existe un num declarado en la funcion second o first, nonlocal enlaza a ese num y las operaciones de asignacion afectan esa variable envolvente. Si no existe ninguna vinculacion en las funciones envolventes aparece SyntaxError porque nonlocal exige una vinculacion previa en un ambito de funcion.

Sin declarar global ni nonlocal, la resolucion de nombres sigue el orden LEGB: primero Local, luego Enclosing, luego Global y por ultimo Builtins. Esto significa que una referencia a num dentro de third buscara primero una variable local en third, luego en las funciones envolventes, luego en el modulo y por ultimo en builtins. Si dentro de third se asigna a num sin declarar nonlocal o global, Python tratara num como variable local y si antes de asignarla se intenta leer su valor se producira UnboundLocalError porque la variable local no tiene aun un valor asociado.

No se puede combinar global y nonlocal para el mismo nombre dentro de la misma funcion. El intento de declarar global num y nonlocal num en la misma funcion produce un SyntaxError porque el nombre no puede ser a la vez no local y global.

Ideas practicas y recomendaciones: para modificar un contador que vive en el modulo declare global dentro de la funcion que lo cambia. Para modificar una variable definida en una funcion envolvente declare nonlocal. Evite confusiones al mezclar variables de clase y variables de instancia: los nombres definidos dentro del bloque de clase no se consideran ambitos de funcion para nonlocal, y a menudo es mas claro acceder a atributos de instancia mediante self.nombre.

Errores tipicos a vigilar: NameError cuando se referencia un nombre global inexistente, UnboundLocalError cuando una asignacion convierte un nombre en local y se intenta leer antes de asignarlo, y SyntaxError cuando se usa nonlocal sin una vinculacion en una funcion envolvente o cuando se declaran nonlocal y global para el mismo nombre.

En Q2BSTUDIO aplicamos buenas practicas de desarrollo para evitar este tipo de errores en proyectos reales. Somos una empresa de desarrollo de software que ofrece aplicaciones a medida y software a medida diseñados para escalar y ser mantenibles. Integramos soluciones de inteligencia artificial e implementamos agentes IA e IA para empresas que automatizan y optimizan procesos. Nuestros servicios incluyen ciberseguridad, servicios cloud aws y azure y servicios inteligencia de negocio que aprovechan herramientas como power bi para ofrecer dashboards y analitica avanzada.

Si necesitas ayuda para diseñar una arquitectura de software limpia, implantar controles de seguridad, desplegar modelos de inteligencia artificial o crear aplicaciones a medida contacta con Q2BSTUDIO. Podemos asesorarte en integracion con servicios cloud aws y azure, en proyectos de inteligencia artificial para empresas, en agentes IA personalizados y en desarrollos que utilicen power bi para reporting e inteligencia de negocio.

Palabras clave: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

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