Welcome to the second edition of this weekly series where we look at the surprising sides of programming languages. Today we have a look at some Python features. Whether you write Python daily or just encounter it occasionally, there are a few design decisions in the language that are worth understanding in detail. They affect how your code behaves in ways that are not always obvious. Python allows you to set default values for function parameters. This is a common and useful feature. What surprises many developers is that mutable default values, such as lists or dictionaries, are created once at function definition time, not each time the function is called. If you define a function with an empty list as a default parameter and then append to it inside the function body, that list persists between calls. The second call sees the data from the first. This is not a bug. Python evaluates default arguments when the def statement is executed, and the resulting object is stored as part of the function. The standard workaround is to use None as the default and create a new list inside the function body. It is a small detail, but it is one of the most frequently encountered sources of unexpected behavior in Python. The second curiosity is the Global Interpreter Lock, commonly known as the GIL. CPython, the reference implementation of Python, uses a mechanism that allows only one thread to execute Python bytecode at a time. This means that even on a machine with multiple CPU cores, threads in a Python program do not run Python code in true parallel. The GIL exists to protect the internal memory management of CPython, which uses reference counting for garbage collection. Without the lock, concurrent reference count updates could corrupt memory. For I/O-bound tasks like network requests or file operations, threading still works well because the GIL is released during I/O waits. For CPU-bound work, the common alternatives are the multiprocessing module, which spawns separate processes each with their own GIL, or libraries like NumPy that release the GIL during heavy computation in C. The third curiosity is that Python uses indentation as part of its syntax. In most languages, indentation is a matter of style. In Python, it determines program structure. A block of code is defined by its indentation level, not by braces or keywords. If the indentation is inconsistent, the program does not run. This was a deliberate design choice by Guido van Rossum to enforce readable code at the language level. It removes an entire category of formatting debates but introduces a constraint that many developers coming from C-style languages find unusual at first. Three aspects of Python that are easy to miss in tutorials but relevant in practice. Next Friday, we continue with a different language. #Python #Programming #SoftwareEngineering #FridayLanguageCuriosities #CodeCuriosities #CPython #GIL #DevCommunity
Python Curiosities: Default Args, GIL, and Indentation
More Relevant Posts
-
✅Python Isn't Easy. You're Just Confusing "Short" with "Simple." I work with Java, C++, and Python. Some people think "hard" means a language that requires writing a lot of code.That's not it, man.Hard means logically challenging not the length of the code. And here's the real truth: most of the time, Python is hard too. Let me explain. C++ hands you complexity on a silver platter. Memory allocation, pointers, manual management it's all explicit. You see the gears turning. When something breaks, you usually know where to look.Python hides all that. So when things go wrong, they go wrong in subtle ways.Memory leaks? Still possible in Python with circular references.Performance bottlenecks? Try profiling a Python app and watch those clean one-liners turn into optimization nightmares.Concurrency? Python's async/await looks clean on the surface, but understanding the event loop, handling coroutines properly, and avoiding blocking calls takes serious logical thinking.Python might be shorter. But short doesn't mean simple. ✅There's a reason computer science and electrical engineering programs use C++ as a first language. They want students to understand the basics and by "basics," I mean what's actually happening under the hood. Memory addresses. Stack frames. Pointer arithmetic. These aren't just academic concepts. They're the foundation.When you write that recursive Fibonacci function in C++, you can almost visualize the call stack growing and shrinking. Each function call has a real cost, a real memory address, real registers being pushed and popped. Python abstracts all that away.Sure, students write Fibonacci faster in Python. But do they really understand recursion? Or are they just copying syntax? That's why engineering programs rarely start with Python. They want you to feel the computer working. The explicit pointer manipulation, the manual memory management it forces you to develop a mental model of how computers actually execute code.Once you have that foundation, picking up Python is easy.But going the other way? Python first students often struggle with concepts like pointers because they've never had to think about memory. Java and C++ are the high performance workhorses. Hard on the outside, honest about their complexity. but Python? Python is the fox who covered himself in sheep's wool. Looks innocent. Feels approachable. But underneath that cozy syntax? Complexity waiting to bite you when you least expect it.So yeah, Python code might be shorter.But understanding what that code actually . #programming #softwareengineering #python #cpp #java #computerscience #coding #Ai #ml
To view or add a comment, sign in
-
-
Understanding How Python Code Runs: From Source Code to Execution When we write Python programs, it may appear that the code runs directly after we execute it. However, behind the scenes, Python follows a well-defined process before producing the final output. Here is a step-by-step overview of how Python code is executed: 1️⃣ Writing the Source Code The process begins when a developer writes Python code in a file with the ".py" extension (for example, "main.py"). This file contains the human-readable instructions written using Python syntax. 2️⃣ Python Interpreter Reads the Code When the program is executed (e.g., "python main.py"), the Python interpreter reads the source code. Unlike compiled languages such as C or C++, Python does not directly convert code into machine code. 3️⃣ Compilation to Bytecode The interpreter first compiles the source code into an intermediate format called bytecode. Bytecode is a low-level, platform-independent representation of the program instructions. 4️⃣ Storage in "__pycache__" The generated bytecode is often stored in the "__pycache__" directory as ".pyc" files. This allows Python to reuse the compiled bytecode in future executions, improving performance. 5️⃣ Execution by the Python Virtual Machine (PVM) Finally, the Python Virtual Machine (PVM) reads the bytecode and executes it instruction by instruction. The PVM acts as a runtime engine that translates bytecode into operations understandable by the underlying system. 📌 In Summary: Python Execution Flow → "Source Code (.py) → Bytecode (.pyc) → Python Virtual Machine → Output" #Python #Programming #SoftwareDevelopment #Coding #PythonInternals #Developers #LearningPython
To view or add a comment, sign in
-
-
Day 5/30 Explaining IDEs, Python & High-Level Languages. Today, I decided to break down three concepts particularly to some of my colleagues who are struggling to really get the whole concept. So first of all when it comes to programming and coding there's something called programming language, best described, you're getting into a new environment ( new country) and you need a language to communicate in that country, for this case the language is called programming language. There are a lot of programming languages out there, but we are going to be using a language called Python ( because of the state, in the country that we're in 😁) Now… 🔶What is Python? Python is a programming language, but what does that mean? A programming language is simply a way humans give instructions to computers. Python is considered: 🔸Easy to read 🔸Simple to write 🔸Very powerful What makes Python special is that its syntax(the structure of statements in a computer language) looks close to normal human language. Example: print("Hello World") Even a beginner can guess what that does. That’s the beauty of Python. Because of the ability of python to be close to human reading and writing, it is seen as a high level language, so… 🔶What is a High-Level Language? To understand this, imagine two scenarios: 🔸Talking to a human in English 🔸Talking to a machine in pure binary (0s and 1s) Machines only understand binary. High-level languages like Python act as a bridge between humans and machines. They allow us to write instructions in a way that is easy for humans to understand, and then the computer translates it behind the scenes. Lastly, for now, There's an environment that all these needs to be executed, you need the right environment to write and run your code, just as how you need the right environment to tweet and post 🤏 right? That will us to what is called an IDE 🔶What is an IDE? IDE stands for Integrated Development Environment, does that sound too complex? An IDE is your coding workspace. It’s where you: 🔸Write your code 🔸Run your code 🔸Debug errors 🔸Manage files Think of it like Microsoft Word, but instead of writing essays, you’re writing code. Some common Python IDEs include: 🔸Visual Studio Code 🔸PyCharm 🔸Jupyter Notebook 🔸Google Colab There's a full package option called Anaconda Each has its strengths. For beginners, tools like Google Colab are great because they run in the cloud and require minimal setup. Why This Matters in Data Science Before jumping into machine learning models, dashboards, and complex analysis… We must understand: 🔸The language you’re using 🔸The environment you’re working in 🔸And how your code communicates with the machine Strong fundamentals reduce confusion later, and confusion is what makes many beginners quit. I’m still early in my journey, but I’m choosing clarity over speed, and of course I can't wait to BE THE BEST AT WHAT I DO. TS Academy #DataScience #LearningWithTs #30DaysOfTech
To view or add a comment, sign in
-
-
The Python GIL. The most misunderstood part of Python. Many developers say Python cannot do multithreading because of the Global Interpreter Lock. That statement is only partially true. To understand the GIL, we first need to understand how CPython executes code. CPython is not inherently thread safe. Many internal operations such as reference counting modify shared memory structures. If multiple threads modified these structures simultaneously, the interpreter could easily corrupt memory or crash. To prevent this, CPython uses a global mutex called the Global Interpreter Lock. The rule is simple. At any moment, only one thread is allowed to execute Python bytecode. Even if you create multiple threads using the threading module, they must take turns holding the GIL before executing Python instructions. This means CPU bound Python threads do not truly run in parallel. Example import threading def task(): for _ in range(10**7): pass t1 = threading.Thread(target=task) t2 = threading.Thread(target=task) t1.start() t2.start() t1.join() t2.join() Even though two threads are created, only one thread runs Python bytecode at a time because of the GIL. So why does Python still support threads? Because the GIL is released during blocking operations. When Python performs operations such as file reading, network requests, or database queries, the interpreter temporarily releases the GIL. This allows another thread to run while the first thread waits for the operating system. Example scenarios where threads work well Network requests File I O Database queries External API calls In these situations, Python threads can provide real concurrency because most of the time is spent waiting for external systems. Another interesting detail is how thread switching happens. CPython periodically forces a thread to release the GIL after executing a certain number of bytecode instructions. This mechanism prevents one thread from monopolizing the interpreter. In modern Python versions, the interpreter also checks time based intervals to decide when to switch threads. This gives other threads the chance to acquire the lock and continue execution. So the real impact of the GIL depends on the type of workload. CPU bound workloads such as heavy computation or numerical loops will not benefit from multithreading in CPython. I O bound workloads can still scale very well using threads. For CPU heavy workloads, developers usually rely on Multiprocessing which runs separate processes with separate interpreters Native extensions written in C that release the GIL Libraries like NumPy that perform computation outside the interpreter Interestingly, the GIL also simplifies CPython’s design. Because only one thread executes bytecode at a time, many internal data structures do not require complex locking mechanisms. This keeps the interpreter simpler and often faster for single threaded workloads.
To view or add a comment, sign in
-
-
What is the use of self in Python? If you are working with Python, there is no escaping from the word “self”. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method. The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python. self is a parameter in function and the user can use a different parameter name in place of it. Although it is advisable to use self because it increases the readability of code. In Python, self is the keyword referring to the current instance of a class. Creating an object from a class is actually constructing a unique object that possesses its attributes and methods. The self inside the class helps link those attributes and methods to a particular created object. Self in Constructors and Methods self is a special keyword in Python that refers to the instance of the class. self must be the first parameter of both constructor methods (__init__()) and any instance methods of a class. For a clearer explanation, see this: When creating an object, the constructor, commonly known as the __init__() method, is used to initialize it. Python automatically gives the object itself as the first argument whenever you create an object. For this reason, in the __init__() function and other instance methods, self must be the first parameter. If you don’t include self, Python will raise an error because it doesn’t know where to put the object reference. Is Self a Convention? In Python, instance methods such as __init__ need to know which particular object they are working on. To be able to do this, a method has a parameter called self, which refers to the current object or instance of the class. You could technically call it anything you want; however, everyone uses self because it clearly shows that the method belongs to an object of the class. Using self also helps with consistency; hence, others-and, in fact, you too-will be less likely to misunderstand your code. Why is self explicitly defined everytime? In Python, self is used every time you define it because it helps the method know which object you are actually dealing with. When you call a method on an instance of a class, Python passes that very same instance as the first argument, but you need to define self to catch that. By explicitly including self, you are telling Python: “This method belongs to this particular object.” What Happens Internally when we use Self? When you use self in Python, it’s a way for instance methods—like __init__ or other methods in a class—to refer to the actual object that called the method. #Python #Data_analaysis
To view or add a comment, sign in
-
Don't let anyone tell you that Python is slow. Sure, it may not be as fast as compiled languages, but with these steps i promise you won't be able to tell the difference. 1. Use Built In Functions. Why? Simply because they are written in C, the old saying "if you can't beat them can join them" is true. 2. Use Generators. By using the "yield" keyword, you can turn functions into iterative generator functions. This extremely beneficial for large datasets since it prevents from having to do expensive memory allocation, which can heavily impact performance. 3. Use Concurrency. You literally cloning yourself to get twice as much done. A good number of problems can be solved with concurrency, and you can use that through the "multiprocessing" library. 4. Compile your code with Cython. it's not replacement for Python but it can optimize certain parts of your code base to improve the overall performance. 5. Use compiled frameworks/libraries The popular libraries like Numpy, pandas, and pillow are all implemented using C under the hood, so use them as much as you can. 6. Use uv uv is an extremely fast Python package and project manager written in Rust, it replaces the old pip, and it's 10-100x Faster than pip. 4 years coding with Python, i manged to make it faster if not as fast as the popular compiled languages.
To view or add a comment, sign in
-
-
Tutorial on Python's Conditional Statements (If-Else) In Python allow your program to make decisions and execute specific blocks of code based on whether a given condition evaluates to True or False. They are fundamental for controlling the flow of a program and handling different inputs or scenarios. ### 1. If Statement (2:45) Purpose: The if statement is used to test a single condition and execute a block of code only if that condition evaluates to True. If the condition is False, the code block associated with the if statement is skipped, and nothing is executed. Syntax: python if condition: # Code to be executed if the condition is True Important Points: The code inside the if block must be indented. This indentation is crucial for Python to understand the code structure. Conditions typically involve comparison operators (e.g., > , < , == ) which return a True or False boolean value. Example: python age = 26 if age > 19: print("You are an adult.") # Output: You are an adult. If age was 15, there would be no output. ### 2. If-Else Statement Purpose: The if-else statement provides an alternative block of code to execute if the if condition is False. This ensures that something happens regardless of whether the initial condition is true or false, avoiding empty outputs. Syntax: python if condition: # Code to be executed if the condition is True else: # Code to be executed if the condition is False Important Points: The else block does not require a condition because it automatically executes when the if condition is false. Example: python temperature = 30 if temperature < 25: print("It's a cool day!") else: print("It's a hot day!") # Output: It's a hot day! (since 30 is not less than 25) ### 3. If-Elif-Else Statement Purpose: This statement allows for checking multiple conditions sequentially. It provides a way to handle more complex scenarios where there are several possible outcomes based on different conditions. Python checks conditions from top to bottom, executing the code block for the first True condition it encounters. Syntax: python if condition1: # Code if condition1 is True elif condition2: # Code if condition2 is True (and condition1 was False) else: # Code if all preceding conditions were False Important Points: You can have multiple elif blocks. The else block is optional but provides a fallback for all cases where no if or elif condition is met. Example: python marks = int(input("Enter your marks (out of 100): ")) if marks >= 90: print("Grade A+") elif marks >= 80: print("Grade A") elif marks >= 70: print("Grade B") else: print("Grade C") # Example Input: 77 --> Output: Grade B # Example Input: 91 --> Output: Grade A+ #Python #Programming #ConditionalStatements #IfElse #Coding #TechEducation Continue..
To view or add a comment, sign in
-
Important Methods Every Python Developer Should Know While learning Object-Oriented Programming in Python, I realized that not all methods inside a class behave the same. Python provides three powerful types of methods that help us organize code better: ✔ Instance Methods ✔ Class Methods ✔ Static Methods Let’s understand them in a simple way 👇 --- 🔹 1. Instance Method Instance methods work with object data. • They access instance variables • The first parameter is always self Example: class Student: def __init__(self, name): self.name = name def display(self): print("Student Name:", self.name) s = Student("Vamshi") s.display() 📌 Instance methods are used when we want to work with object-specific data. --- 🔹 2. Class Method Class methods work with class variables instead of object variables. • Defined using @classmethod • The first parameter is cls Example: class Student: college = "BITS College" @classmethod def show_college(cls): print("College:", cls.college) Student.show_college() 📌 Class methods are useful when working with data shared by all objects. --- 🔹 3. Static Method Static methods are independent methods. • They don’t use self or cls • Defined using @staticmethod Example: class Calculator: @staticmethod def add(a, b): return a + b print(Calculator.add(5, 7)) 📌 Static methods are used for utility functions related to a class. Instance Method → Works with object data Class Method → Works with class data Static Method → Independent helper function Understanding these concepts helps us write clean, structured, and scalable Python code. 📚 Learning OOP step by step every day. #Python #OOP #PythonProgramming #CodingJourney #SoftwareDevelopment #LearnPython
To view or add a comment, sign in
-
-
Can you write raw C code directly inside a Python script? ========================================= Because the standard Python interpreter (CPython) is written in C, there is a persistent myth floating around: "Since Python is built on C, you can just drop a C code or a low-level system call directly into your .py file". If you try this, the interpreter will instantly hit you with a SyntaxError. Here is the logical breakdown of why this myth is false — and how the two languages actually interact: ⚙️ The Role of python.exe When you execute a Python script, you are running python.exe (or the CPython binary on Linux). This executable is a compiled C program. Its exact job is to read Python syntax, compile it into intermediate bytecode, and evaluate it inside a virtual machine loop. Crucially, python.exe is an interpreter, not a C compiler. It has absolutely no built-in mechanism to parse, compile, or execute raw C text on the fly. ❌ The Architectural Mismatch Python and C operate on fundamentally incompatible execution models: 1. C is Compiled: It requires a compiler (like GCC or Clang) to translate the source text entirely into raw, architecture-specific machine code before execution. 2. Python is Interpreted: The CPython executable reads Python syntax, compiles it to intermediate bytecode, and evaluates it inside a virtual machine. It does not contain a built-in C compiler to parse raw C text on the fly. ✅ The Real Solution: The Bridge When engineers say they are “using C in Python,” they are not mixing the syntax. They are keeping the stacks strictly separate: 1. Write your performance-critical code or system calls in C. 2. Compile that C code into a shared binary library (.so or .dll). 3. Use Python's built-in ctypes or the Python C-API to load and interface with that compiled binary. 👉 You get the strict, blazing-fast execution of C for the heavy lifting, combined with the rapid development speed of Python for the middleware layer.
To view or add a comment, sign in
-
-
🐍 Understanding __init__.py in Python (And Why It Still Matters) If you’ve read enough Python code—especially in large projects—you’ve probably seen __init__.py everywhere. Most developers know it has something to do with packages. But many are still unsure: ❓ Is it still required in modern Python? ❓ What exactly does it do? ❓ Why do imports sometimes behave strangely around it? Let’s clear that up. 📦 What __init__.py Used to Do In earlier versions of Python, __init__.py had a simple role: ➡️ It marked a directory as a Python package. Without it, Python wouldn’t recognize the folder as importable. Today, modern Python allows directories to function as packages even without __init__.py. But that doesn’t mean the file is obsolete. ⚙️ Why __init__.py Is Still Useful It still serves two important purposes: 1️⃣ Package Initialization __init__.py runs the first time the package is imported. This makes it a great place for package-level setup or configuration. 2️⃣ Creating a Clean Public API You can expose the main functions, classes, or variables you want users to import directly. Instead of writing: from utils.math_util import add You can structure __init__.py so users simply write: from utils import add This keeps your package cleaner and easier to use. ⚠️ The Import Confusion Many Developers Hit Consider a package structure like this: utils/ ├── __init__.py └── math_util.py From outside the package, this works: from utils.math_util import add But inside __init__.py, writing this may break: from math_util import add Instead, you should use a relative import: from .math_util import add That small . tells Python: ➡️ Look inside the current package. And that tiny detail is often where confusion begins. 🧠 A Practical Tip When imports start breaking: 🔎 Don’t just stare at the import statement. Instead check: - your package structure - your entry point file - the import context More often than not, that’s where the real issue lives. Clean package design is one of those small skills that make a big difference in maintainable Python projects. 💬 Have you ever run into confusing import issues in Python packages? What helped you debug them? #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #DeveloperTips #Coding
To view or add a comment, sign in
-
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
that mutable default trap caught me early on too. had to re-learn how the function scope worked for that.