🚀 Python Tip: Using default_factory in Dataclasses While working on a data quality framework in Python, I encountered an interesting scenario with timestamps. I wanted every new instance of my dataclass to have a fresh, current timestamp. At first, I tried this: from dataclasses import dataclass, field from datetime import datetime, timezone @dataclass class QualityCheckResult: timestamp: datetime = datetime.now(timezone.utc) # ❌ The problem? Every instance got the same timestamp — Python evaluated it once when the class was defined. Not what I wanted! The solution: default_factory @dataclass class QualityCheckResult: timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) # ✅ Why this works: default_factory expects a callable (like a lambda or function) Python stores the callable, but doesn’t run it immediately Every time you create a new object, Python calls the lambda, producing a fresh timestamp 💡 Think of it as keeping a “recipe” instead of the finished product. Each object gets its own freshly baked “timestamp” instead of reusing the same one. This small tweak solves a subtle bug and ensures my data quality logs always reflect the exact creation time. Python’s dataclasses + default_factory = cleaner, bug-free defaults! ⚡
Python Tip: Using default_factory in Dataclasses
More Relevant Posts
-
Dictionary vs List — Lookup Speed in Python Checking whether an element exists in a collection is one of the most common operations in Python. But the performance of this operation depends heavily on the data structure being used. I compared lookup speed between a List and a Dictionary while working with a large dataset. What Happens Behind the Scenes List: - A list stores elements in sequence. - When Python checks if a value exists in a list, it searches elements one by one until it finds a match. - This process is called linear search, which becomes slower as data size increases. Dictionary: - A dictionary stores data using hashing. - Instead of scanning every element, Python directly jumps to the location of the key. - This allows dictionaries to perform lookups much faster, especially for large datasets. Observations: • List lookup checks elements sequentially. • Dictionary lookup uses hashing. • Performance difference increases as dataset size grows. Using dictionaries for frequent lookups is very useful in real-world scenarios like caching, indexing, and fast data retrieval. Note: time.perf_counter() is preferred for performance testing because it provides more precise timing compared to time.time(). Which one do you usually use for fast lookups — List or Dictionary?
To view or add a comment, sign in
-
-
Python Functions: A function is a block of organized, reusable code and that us used perform a single used and multiple tasks. Syntax: def calculate(a,b): Recurstion:In Python, recursion refers to a function calling itself to solve a problem. It involves two critical components: Base case: This is the condition that terminates the recursion. Difference between print and Return: print just stored the human user output in a control. Return:-is keyword and return used to terminate the function and gives that a value the function. Return only one time call the function because terminate the value. Keyword and positional arguments: number of values and keyword accepted to jumbling order also accepted. Default arguments: already existed non default followed. *arguments: Is used to unpack the elements only should pass single * arguments. Variable length arguments of automatically stored in tuple and used * arguments. **keywards of automatically stored in dictionary and used * arguments. Global and Local variables: A variable inside and outside function is called global and local variables. Usage of global Keywords: When user want to access the global variable inside the function directly and carry farward the updated value given outside the function then we need to used global keyword. Generators: No tuples comprehension in above cases if we remove don't spaces and key parameter than out coming generators. A generators is also a function which can be used as an loops by producing group of values, variable used yield keywords. Yield/Return: Return keyword terminate the function where as yield can pass function and go on the every function iteration Pooja Chinthakayala Mam,Saketh Kallepu Sir,Uppugundla Sairam Sir.
To view or add a comment, sign in
-
⚠️ Naming Conflict in Python (datetime) You wrote: import datetime datetime = a + 1 This creates a naming conflict ❌ 🧠 What’s Happening? datetime is both: 📦 A built-in Python module → datetime 🏷️ A variable name you created When you assign: datetime = a + 1 You overwrite the module with an integer (or other value). After this, Python no longer sees the module 😱 ❌ Example of the Problem import datetime datetime = 5 print(datetime.datetime.now()) 👉 Error: AttributeError: 'int' object has no attribute 'datetime' Because datetime is now an integer, not the module. ✅ Correct Ways to Fix It ✔️ Option 1 — Use a Different Variable Name (Best) import datetime value = a + 1 Never use names of modules, classes, or built-ins for variables. ✔️ Option 2 — Import Specific Class from datetime import datetime now = datetime.now() Now datetime refers to the class, not the module. ✔️ Option 3 — Use an Alias import datetime as dt dt_value = a + 1 print(dt.datetime.now()) Aliases are very common in professional code. 🚫 Names You Should Avoid Using as Variables datetime time list str dict id type sum These override built-ins or modules. 🏆 Best Practice 👉 Use descriptive variable names: next_value = a + 1 result = a + 1 counter = a + 1
To view or add a comment, sign in
-
Python Study Day 3 *Input and Output in Python - Input from the User: In Python, we use the input() function to take input from the user. The data entered by the user is always received as a string, so if you want to use it as a different data type (e.g., integer or float), you'll need to convert it using type conversion functions like int() or float(). name = input("Enter your name: ") age = int(input("Enter your age: ")) # Convert input to integer - Output to the Console: The print() function is used to display output to the console. You can use it to display text, variables, or results of expressions. print("Hello, " + name + "! You are " + str(age) + " years old.") You can also use f-strings (formatted string literals) for more readable code: print(f"Hello, {name}! You are {age} years old.") - Comments in Python Comments are ignored by the Python interpreter and are used to explain the code or leave notes for yourself or others. They do not affect the execution of the program. Single-line comments start with #: # This is a single-line comment print("Hello, World!") Multi-line comments can be written using triple quotes (""" or '''). These are often used to write detailed explanations or temporarily block sections of code: """ This is a multi-line comment. It can span multiple lines. """ print("Hello, Python!") - Escape Sequences Escape sequences are special characters in strings that start with a backslash (\). They are used to represent certain special characters. Some commonly used escape sequences: \n: New line \t: Tab space \\: Backslash Example: print("Hello\n World") # Output: # Hello # World print("Hello\t Python") # Output: Hello Python
To view or add a comment, sign in
-
🌦️ Built one more script using Python - **DuckDuckGo Top Search Result CLI Tool** (last project of edureka). I made a script using Python that fetches real-time top search result data of DuckDuckGo search engine for any query using "ddgs library of python" as one of the final project given by Edureka The program accepts a argument as query to search in duckduckgo search engine, and returns the required top search results, not only title and urls - it will provide you the top videos and all corresponding details like published_date, publisher, embed_urls, thumbnail_images of different resolutions and many more and at last you can save these data in a file. Tech Used: Python, JSON parsing, duckduckgo-search (ddgs), AsyncIO Features: ✅ accepting query by CLI ✅ current top required search results ✅ You can choose how many results you want to fetch ✅ Get all data - Title, URL, Publisher, Publishing date, images, Provider, Uploader, Video urls and many more ✅ Facility to save these data into a file (with the timestamp and the query) ✅ Clean terminal formatting ✅ Async execution for better structure This project strengthened my understanding of working with external services, handling responses, and building practical automation tools. All scripts available in my github profile - https://lnkd.in/gJGmqXme
To view or add a comment, sign in
-
Ever wondered why your Python script slows down when your data grows? 🐍 I used to think of Lists and Dictionaries as just simple "containers," but digging into how Python handles memory "under the hood" changed my perspective on writing efficient code. In my latest blog post, I break down: 🔹 The "Moving Day" problem: How Lists actually grow in memory. 🔹 The Library GPS: Why Dictionaries are so much faster than Lists. 🔹 Why Tuples are the lightweight "speedsters" of Python. If you're a student or developer looking to move from just "making it work" to "making it smart," this one is for you. #Python #Coding #DataStructures #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
What is the difference between list, tuple and array in Python? This content distinguishes between Python's lists, tuples, and arrays. Lists are mutable and flexible, ideal for frequent changes. Tuples are immutable for fixed data, while arrays are efficient for numerical data, requiring uniform data types. Understanding these differences aids in writing cleaner Python code and optimizing data management....
To view or add a comment, sign in
-
What is the difference between list, tuple and array in Python? This content distinguishes between Python's lists, tuples, and arrays. Lists are mutable and flexible, ideal for frequent changes. Tuples are immutable for fixed data, while arrays are efficient for numerical data, requiring uniform data types. Understanding these differences aids in writing cleaner Python code and optimizing data management....
To view or add a comment, sign in
-
FOSDEM, room 'Python': 1. PEP 810: Lazy Imports. One of the most anticipated Python proposals targeting Python 3.15. PEP 810 introduces a new "lazy" keyword that defers module loading until first use, instead of at import time. This can cut startup time by 50-70% for CLI tools and applications with large dependency graphs. The Python Steering Council has already greenlighted it :D. Some caveats to keep in mind though: import-time side effects shift to first use, type checkers need updates, and missing dependencies are only discovered at runtime. The recommendations: "Keep eager imports for always-used packages". "Explicit is better than implicit". 2. The GIL and API Performance: Past, Present, and Free-Threaded Future. A deep dive into Python's Global Interpreter Lock, the mechanism that has limited true multi-threaded parallelism for almost three decades. Multiple past attempts to remove it failed because the trade-offs in single-threaded performance were too steep. But with Python 3.14, free-threaded mode is now officially supported (no longer experimental), with only about 5-10% overhead on single-threaded code. You can try it today with uv run -p 3.14t. For API developers, this means real parallel request processing using threads instead of workarounds like multiprocessing. I hope you find this useful for future projects. Let Python go brrrrrrr
To view or add a comment, sign in
-
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
Interesting 👏