Data-Types

The capabilities of data-types in different languages.

Python Data-Types


Primitive Types

Basic data types provided by the language (e.g., integers, floats, strings).

Structured Data Type Definitions (Dataclasses, Dictionaries, TypedDict)

Python supports structured data using dataclasses, dictionaries, and TypedDict.

Using dataclasses (preferred for structured data):

from dataclasses import dataclass from typing import Optional @dataclass class User: id: int name: str email: Optional[str] = None # Optional field user = User(id=1, name="Alice")

Using TypedDict (for dictionary-based structures):

from typing import TypedDict class Product(TypedDict, total=False): # `total=False` makes fields optional id: int name: str price: float category: str item: Product = {"id": 101, "name": "Laptop", "price": 1200.0}

Error Loading

Missing


Structured Data Type Definitions

Definitions for structured data types like Dataclasses, Dictionaries, or TypedDict.

Classes

class Person: def __init__(self, name: str): self.name = name print(f"{self.name} is created") def greet(self): print(f"Hello, my name is {self.name}") def __del__(self): print(f"{self.name} is deleted") person = Person("Alice") person.greet() del person # Explicitly triggering destructor (not always necessary)

Missing


Classes

Blueprints for creating objects with attributes and methods.

Class Property Accessors

class Person: def __init__(self, name): self._name = name # Private attribute convention (_name) @property def name(self): """Getter method""" return self._name @name.setter def name(self, value): """Setter method""" if not value: raise ValueError("Name cannot be empty") self._name = value @name.deleter def name(self): """Deleter method""" print("Deleting name...") del self._name # Usage p = Person("Alice") print(p.name) # Getter: Output -> Alice p.name = "Bob" # Setter print(p.name) # Output -> Bob del p.name # Deleter

Missing


Class Property Accessors

Methods to get or set class properties.

Class Generics

from typing import Generic class Box(Generic[T]): def __init__(self, content: T): self.content = content def get_content(self) -> T: return self.content int_box = Box print(int_box.get_content()) # 10 str_box = Box[str]("Python") print(str_box.get_content()) # "Python"

Missing


Class Generics

Support for generic programming with classes.

Class Inheritance

class Animal: def __init__(self, name: str): self.name = name def make_sound(self): print("Some generic animal sound") class Dog(Animal): def __init__(self, name: str): super().__init__(name) # Calls parent constructor def make_sound(self): print("Woof!") dog = Dog("Buddy") dog.make_sound() # "Woof!"

Abstract classes defined using abc module:

from abc import ABC, abstractmethod class Speakable(ABC): @abstractmethod def speak(self): pass # Must be implemented by subclasses class Robot(Speakable): def speak(self): print("Beep boop!") bot = Robot() bot.speak() # "Beep boop!"

Missing


Class Inheritance

Mechanism to create a new class from an existing class.

Enum Definitions

Python's enum module allows defining enumerations.

from enum import Enum class Status(Enum): PENDING = "Pending" IN_PROGRESS = "In Progress" COMPLETED = "Completed" current_status = Status.IN_PROGRESS
  • Enum values can be strings, numbers, or other types.

Missing


Enum Definitions

Define a set of named constants.

Type Casting in Python

Python supports type casting (type conversion) to convert data from one type to another. It also provides mechanisms for type checking and dynamic type handling.

Explicit Type Conversion : - Python allows explicit type conversion using built-in functions like int(), float(), str(), etc.

# Convert between types a = "42" b = int(a) # Convert string to integer c = float(b) # Convert integer to float d = str(c) # Convert float to string print(a, b, c, d) # Output: "42" 42 42.0 "42"
  • Type conversion is explicit and must be performed using the appropriate function.
  • Incompatible conversions (e.g., converting a non-numeric string to an integer) will raise a ValueError.

Python provides the type() function to check the type of a variable. For more robust type checking, you can use the isinstance() function.

x = 42 y = "hello" print(type(x)) # Output: <class 'int'> print(type(y)) # Output: <class 'str'> # Using isinstance() if isinstance(x, int): print("x is an integer") # Output: x is an integer
  • type() returns the type of the variable.
  • isinstance() checks if a variable is an instance of a specific type or a tuple of types.

Python is dynamically typed, meaning variables can hold values of any type, and their type can change at runtime.

x = 42 print(type(x)) # Output: <class 'int'> x = "hello" print(type(x)) # Output: <class 'str'>

You can use isinstance() in a conditional statement to check and handle types dynamically.

def process_value(value): if isinstance(value, int): print(f"Integer: {value}") elif isinstance(value, str): print(f"String: {value}") else: print("Unknown type") process_value(42) # Output: Integer: 42 process_value("hello") # Output: String: hello process_value(3.14) # Output: Unknown type

Python supports type hints using the typing module, which allows you to specify the expected types of variables, function arguments, and return values. This is useful for static type checking with tools like mypy.

from typing import List def add_numbers(a: int, b: int) -> int: return a + b def process_list(items: List[int]) -> None: for item in items: print(item) result = add_numbers(10, 20) process_list([1, 2, 3])
  • Type hints do not enforce types at runtime but help with code readability and static analysis.

Missing


Type Casting

Convert a value from one type to another.

Missing

Missing