Aprende Python desde JS/TS

Guía para desarrolladores que pasan de JavaScript/TypeScript a Python 3.10: sintaxis, tipos, concurrencia y patrones prácticos; descubre cómo Q2BSTUDIO impulsa IA, ciberseguridad y servicios cloud a medida.

11 sept 2025 • 6 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Este artículo está pensado para desarrolladores con experiencia en JavaScript o TypeScript que quieren aprender Python 3.10. Incluye comparativas prácticas sobre sintaxis, tipos, manejo de concurrencia y patrones que facilitan la transición. Además presentamos cómo Q2BSTUDIO puede apoyar en proyectos de software a medida y soluciones basadas en inteligencia artificial, ciberseguridad y servicios cloud.

Sobre Q2BSTUDIO: somos una empresa de desarrollo de software y aplicaciones a medida especializada en inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios de inteligencia de negocio y automatización. Si necesitas construir soluciones de aplicaciones a medida o integrar modelos y agentes IA para empresas consulta nuestros servicios de inteligencia artificial.

Variables: Python no requiere let const o var. La inferencia o anotaciones de tipo son opcionales. Ejemplos: TypeScript let x: number = 5 const y = hello var z = true Python x: int = 5 y: str = hello z = True

Tipos de datos: TypeScript number equivale a int o float en Python; string a str; boolean a bool; any a Any desde typing; arrays a list y tuplas a tuple. Objetos en TS son dict en Python. Ejemplos Python arr: list[int] = [1, 2, 3] tup: tuple[str, int] = (a, 1) obj: dict[str, int] = {name: Alice, age: 25}

Mutabilidad y paso por referencia: listas y diccionarios son mutables y al pasarlos a funciones se pasan por referencia, los cambios afectan al original. Tipos inmutables como int float str y tuple no se pueden mutar in place.

Funciones: TypeScript function add(a: number, b: number): number { return a + b } y arrow (a, b) => a + b. Python def add(a: int, b: int) -> int: return a + b y lambda a, b: a + b. Las lambdas en Python son expresiones para funciones pequeñas; para múltiples sentencias usa def.

Control de flujo: en Python la indentacion define bloques. Ejemplo if x > 5: print(yes) else: print(no). No se usan llaves ni punto y coma.

Bucle for y while: Python usa for in y range para contar. Ejemplos for i in range(5): print(i) for num in arr: print(num) i = 0 while i < 5: print(i) i += 1. Para índices usar enumerate.

Clases y OOP: Python usa self en métodos en lugar de this. No hay palabras reservadas public o private; la convención es _nombre para atributos privados. No se necesita new para instanciar. Ejemplo class Person: def __init__(self, name: str): self.name = name def greet(self): print(Hello + self.name) p1 = Person(Alice) p1.greet()

Herencia: Python permite herencia simple y múltiple y resuelve conflictos con MRO. Uso de super: super().__init__(). Ejemplo class Dog(Animal): def speak(self): print(self.name + barks)

Módulos e imports: en TypeScript debes exportar explícitamente. En Python todo es importable por defecto salvo que se oculte con convenciones o la variable __all__. Ejemplo from os import read o import mi_modulo.

Manejo de excepciones: estructuras equivalentes pero con except en lugar de catch. Ejemplo try: risky_operation() except Exception as err: print(err) finally: cleanup()

Async await: Python usa async def y await sobre corutinas. Con librerías como aiohttp realizas requests sin bloquear el hilo principal. Ejemplo async def fetch_data(): async with session.get(url) as resp: return await resp.text()

Unpacking y operadores spread rest: Python usa * para listas y ** para diccionarios. Para funciones variádicas usa *args y **kwargs. Ejemplos arr2 = [0, *arr1, 4] obj2 = {**obj1, c: 3} def sum_all(*nums: int) -> int: return sum(nums)

Desestructuración: Python no tiene object destructuring como en JS pero permite sequence unpacking. Ejemplos a, b, c = 1, 2, 3 a, *rest = [1, 2, 3, 4]

Interfaces: Python no tiene keyword interface; para contratos estrictos usa Abstract Base Classes o Protocols desde typing, aunque el patrón habitual es duck typing y tipado gradual.

Hoisting y scopes: en Python no existe hoisting. Las estructuras if for while no crean un nuevo scope, las funciones sí. Para modificar variables externas dentro de una función anidada usa nonlocal o global según el caso.

Closures: funcionan capturando variables externas. Para modificar variables del scope superior desde una función interna hay que declarar nonlocal.

Corutinas y event loop: una corutina se define con async def y puede pausar su ejecución con await, cediendo el control al event loop. Para ejecutar corutinas desde el entry point usa asyncio.run.

Futures y concurrencia: un Future es similar a una Promise. En asyncio creas tareas con asyncio.create_task que devuelven un Future y se awaitan para obtener resultados.

Comparativa event loop JS vs asyncio: ambos usan un loop de eventos y tareas asíncronas, pero JS tiene microtasks y macrotasks y está estrechamente integrado con Promises; asyncio usa corutinas y futures. Para trabajo paralelo en Python se usan threading para I O bound y multiprocessing para CPU bound debido al GIL en CPython.

GIL: el Global Interpreter Lock evita que varios hilos ejecuten bytecode al mismo tiempo en CPython. Esto limita la paralelización de CPU bound con hilos, por eso se recurre a multiprocessing para cargas intensivas en CPU.

Decoradores: son funciones que envuelven otras funciones o clases para modificar comportamiento. Sintaxis @decorador sobre la función o sobre la clase. Ejemplo def log(func): def wrapper(*args, **kwargs): print(Calling, func.__name__) return func(*args, **kwargs) return wrapper

Propiedades con @property: permite exponer métodos como atributos legibles y configurables con un setter. Ejemplo def name(self): return self._name y @name.setter para validaciones al asignar.

Métodos especiales dunder: __str__ __repr__ __eq__ __add__ __len__ __getitem__ permiten integrar objetos con operadores y funciones integradas, por ejemplo definir una representacion legible o comportamiento de indexado.

Iteradores y generadores: un iterable implementa __iter__ que devuelve un iterator. Un iterator implementa __next__ que lanza StopIteration cuando termina. Los generadores usan yield para producir valores perezosamente. Las comprehensions generan listas de forma eager mientras que las generator expressions son lazy.

Atajos y helper methods: cadenas lower upper strip split join startswith endswith count replace; listas len slice append extend insert remove pop index sort reverse list comprehensions y funciones any all sum map filter reduce; diccionarios get keys values items pop. Estos métodos son equivalentes a helpers comunes en JavaScript pero con diferencias en nombres y comportamiento por defecto.

Conclusión y llamada a la acción: si vienes de JavaScript o TypeScript la mayoría de conceptos son reconocibles pero Python cambia la forma de expresarlos: menos cerrojos sintácticos, tipado opcional, potentes primitivas para concurrencia y una gran biblioteca estándar. Para proyectos donde necesites integrar IA para empresas, agentes IA, soluciones de inteligencia de negocio o desarrollar software y aplicaciones a medida con seguridad y despliegue en cloud, Q2BSTUDIO ofrece servicios completos desde diseño hasta entrega y mantenimiento, incluyendo consultoría en power bi y servicios cloud aws y azure para optimizar despliegues y analítica.

Contacto: consulta nuestros servicios de desarrollo y soluciones empresariales y descubre cómo podemos ayudar a escalar tu producto con software a medida, inteligencia artificial y ciberseguridad.

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