Some of the python powerful feature that will help to write the clean and concise code .
1.Enum
enum (short for enumeration) is a class in the enum module used to define a set of named constant values. It helps make code more readable and less error-prone by grouping related constants together in a clear and structured way.
Introduced in Python 3.4 via the enum module.
Example:
from enum import Enum
class Status(Enum):
DRAFT = "draft"
PUBLISHED = "published"
ARCHIVED = "archived"Usage:
print(Status.DRAFT) # Status.DRAFT
print(Status.DRAFT.value) # "draft"
print(Status.DRAFT.name) # "DRAFT"Why Use Enum?
- Avoid hard-coded strings
- Improve code readability
- Prevent invalid values
- Allow for meaningful comparisons
Iterating Over Enum Members
for status in Status:
print(status.name, status.value)
Comparisons
if some_status == Status.DRAFT:
print("It's a draft.")Note: Enum members are singletons, so is and == both work.
Auto Values (using auto())
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()This will assign values automatically: RED = 1, GREEN = 2, etc.
Customizing Enum Behavior
class Priority(Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
def describe(self):
return f"{self.name} has priority level {self.value}"
Enum with Different Types of Values
You can use str, int, or even tuple as values.
class Response(Enum):
SUCCESS = (200, "Success")
NOT_FOUND = (404, "Not Found")
def __init__(self, code, message):
self.code = code
self.message = message
Enum with Unique Constraint
from enum import Enum, unique
@unique
class Gender(Enum):
MALE = 1
FEMALE = 2
OTHER = 3The @unique decorator ensures that all values are distinct.
2. Decorators
What: Functions that modify other functions.
def my_decorator(func):
def wrapper():
print("Before call")
func()
print("After call")
return wrapper
@my_decorator
def say_hi():
print("Hi")Why Useful:
- Add logging, access control, caching, etc., without changing core logic.
- Heavily used in Flask, FastAPI, Django.
3. Generators & yield
What: Functions that produce a sequence of results lazily.
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1Why Useful:
- Memory efficient for large datasets.
- Helps in pipelines, data streams.
4.typing module
What: Add type hints to functions and classes.
from typing import List, Optional
def greet(name: Optional[str] = None) -> str:
return f"Hello, {name or 'Guest'}"Why Useful:
- Helps with readability.
- Powers tools like Pylance, Mypy.
- Required in Pydantic/FastAPI.
5.async / await
What: Asynchronous programming for non-blocking I/O.
import asyncio
async def main():
await asyncio.sleep(1)
print("Done")
asyncio.run(main())Why Useful:
- Handles many tasks efficiently.
- Core of FastAPI and modern web frameworks.
6. collections module
Provides specialized data structures:
Counterdefaultdictdequenamedtuple
from collections import Counter
c = Counter("hello")
print(c) # {'l': 2, 'h': 1, 'e': 1, 'o': 1}Why Useful: Faster, more expressive than basic dict/list in many cases.
7. user_agents library
The user_agents library in Python is used to parse and extract useful information from user-agent strings. A user-agent string is a part of the HTTP request header sent by a browser or client when making a request to a server. It contains details about the browser, operating system, device, and sometimes the application that made the request.
What is parse in user_agents?
The parse function from the user_agents module is used to extract and interpret a given user-agent string. This allows you to determine details such as the type of device (mobile, tablet, desktop), the browser (Chrome, Firefox, Safari), the operating system (Windows, macOS, Android), and other useful details about the requestor.
Example of usage
from user_agents import parse
# Example user-agent string
user_agent_string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
# Parsing the user-agent string
user_agent = parse(user_agent_string)
# Accessing various properties of the user-agent
print("Browser:", user_agent.browser) # The browser used (e.g., 'Chrome')
print("Browser Version:", user_agent.browser.version) # The version of the browser (e.g., '58')
print("OS:", user_agent.os) # The operating system (e.g., 'Windows')
print("OS Version:", user_agent.os.version) # The version of the operating system (e.g., '10')
print("Device:", user_agent.device) # The type of device (e.g., 'Other')
print("Is Mobile?", user_agent.is_mobile) # Whether it's a mobile device or not (True/False)
print("Is Tablet?", user_agent.is_tablet) # Whether it's a tablet device or not (True/False)
print("Is Desktop?", user_agent.is_pc) # Whether it's a desktop device or not (True/False)
print("Is Touchscreen?", user_agent.is_touch_capable) # Whether the device supports touch (True/False)Common Use Cases:
- Device Detection: You can use this to detect whether a user is accessing your website from a mobile device, tablet, or desktop. This is useful for responsive design or for tracking purposes.
- Browser Analytics: By parsing user-agent strings, you can track which browsers and versions are being used by visitors to your website.
- Customization: You can customize the experience for the user based on their device or browser. For example, showing mobile-optimized content to users with mobile devices.
8.Track User From ip-address
import requests
import pycountry # to get the information frok countrycode
try:
# response = requests.get(f"http://ip-api.com/json/{ip_address}")
token = ''
ip_address=''
response = requests.get(f"https://ipinfo.io/{ip_address}?token={token}")
location_data = response.json()
country_code=location_data.get("country","Unknown")
country = pycountry.countries.get(alpha_2=country_code)
location = {
"city": location_data.get("city","Unknown"),
"country":country.name if country else "Unknown",
}
except Exception:
location = {"city": "Unknown", "country": "Unknown"}
location_data={}
