What's optional[int] in python?
In Python, Optional[int] is a type hint that indicates a value can either be an integer (int) or None. This is useful for functions or variables where the value is not always guaranteed to be an integer and can be absent (represented by None).
The usage of Optional[int] is to provide clear and explicit type annotations in your code, making it easier to understand and maintain. Here are some common scenarios where Optional[int] might be used:
1. Function Parameters
from typing import Optional
def process_value(value: Optional[int]) -> str:
if value is None:
return "No value provided"
return f"Processing value: {value}"
print(process_value(10)) # Output: Processing value: 10
print(process_value(None)) # Output: No value provided
2. Function Return Types
from typing import Optional
def find_value(data: list, key: int) -> Optional[int]:
if key in data:
return data[key]
return None
result = find_value([1, 2, 3], 1)
if result is None:
print("Key not found")
else:
print(f"Found value: {result}")
3. Variable Annotations
from typing import Optional
value: Optional[int] = None
# Later in the code
value = 5 # Now value is an integer
value = None # Now value is None again
4. Class Attributes
Here's a class representing a basic student record where the student's grade might not be initially assigned.
from typing import Optional
class Student:
def __init__(self, name: str):
self.name = name
self.grade: Optional[int] = None # Grade is optional and might not be set
def assign_grade(self, grade: int) -> None:
self.grade = grade
def get_grade(self) -> Optional[int]:
return self.grade
def display_info(self) -> None:
print(f"Student Name: {self.name}")
if self.grade is None:
print("Grade: Not assigned")
else:
print(f"Grade: {self.grade}")
# Usage
student1 = Student("John")
student1.display_info() # Output: Student Name: John, Grade: Not assigned
student1.assign_grade(90)
student1.display_info() # Output: Student Name: John, Grade: 90
student2 = Student("Jane")
student2.display_info() # Output: Student Name: Jane, Grade: Not assigned
"Answer Generated by OpenAI's ChatGPT"