Python Journal 2, 2024
satya - 12/31/2023, 6:27:54 PM
What is the current ver i have?
3.7.4
satya - 12/31/2023, 6:28:20 PM
where is it installed?
c:\satya\i\python374
satya - 12/31/2023, 6:30:49 PM
2024 Jan, Current version
3.12
satya - 2/15/2024, 8:55:33 AM
Making a list behave like a stack
# Creating an empty list to use as a stack
stack = []
# Adding items to the stack (push operation)
stack.append('a')
stack.append('b')
stack.append('c')
print("Stack after pushing items:", stack)
# Output: Stack after pushing items: ['a', 'b', 'c']
# Removing an item from the stack (pop operation)
top_item = stack.pop()
print("Popped item:", top_item)
# Output: Popped item: c
print("Stack after popping an item:", stack)
# Output: Stack after popping an item: ['a', 'b']
satya - 2/15/2024, 8:58:36 AM
This is reverse iteration
stack = ['a', 'b', 'c', 'd']
for item in reversed(stack):
print(item)
satya - 3/9/2024, 11:50:21 AM
Previous version of the journal: Essential Python
satya - 3/9/2024, 12:08:34 PM
Setting type hints for python in vscode
satya - 3/12/2024, 10:48:27 AM
Casting in python
from typing import Any, cast
any_value: Any = get_some_value() # This could be anything
str_value: str = cast(str, any_value)
satya - 3/12/2024, 10:50:58 AM
A function to type assert an object
from typing import Any, Type
def assertType(object: Any, typename: Type[Any], message: str) -> None:
if not isinstance(object, typename):
m=
raise TypeError("write your message")
Example:
assertType(123, int, "Type mismatch")
satya - 3/12/2024, 10:52:23 AM
How do you use this
class TOMLConfig(DictionaryConfig):
def getDictionary(self, args: Any = None) -> Dict[str, Any]:
#validations
log.validate_not_null_or_empty(args)
log.assertType(args,str,"configuration filename needs to be a string")
#casting
configfilename: str = cast(str, args)
return configutils.getTOML_flattened_dictionary(configfilename)
satya - 3/13/2024, 12:07:45 PM
To know if a class is an extension of another: issubclass()
class BaseClass:
pass
class DerivedClass(BaseClass):
pass
# Check if DerivedClass is a subclass of BaseClass
print(issubclass(DerivedClass, BaseClass)) # Output: True
# Check if BaseClass is a subclass of DerivedClass
print(issubclass(BaseClass, DerivedClass)) # Output: False
satya - 3/13/2024, 12:08:37 PM
To know if an instance is of certain type: isinstance()
instance = DerivedClass()
# Check if instance is an instance of DerivedClass or one of its subclasses (if any)
print(isinstance(instance, DerivedClass)) # Output: True
# Check if instance is an instance of BaseClass or one of its subclasses
print(isinstance(instance, BaseClass)) # Output: True
# Using an instance that is not derived from BaseClass
another_instance = BaseClass()
print(isinstance(another_instance, DerivedClass)) # Output: False
satya - 3/13/2024, 12:50:58 PM
One way to use this
class ISingleton():
@staticmethod
def isSingleton(classObj: Type[Any]) -> bool:
return issubclass(classObj,ISingleton)
satya - 3/13/2024, 12:51:40 PM
Even better probably; isSame()
class IExecutor(ABC):
@abstractmethod
def execute(self, config_root_context: str, args: Any) -> Any:
pass
@staticmethod
def isSame(classObj: Type[Any]) -> bool:
return issubclass(classObj, IExecutor)
satya - 3/14/2024, 8:50:15 PM
Loading a class dynamically
@staticmethod
def load_class(fqcn: str) -> Type[Any]:
module_name, class_name = fqcn.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, class_name)
satya - 3/15/2024, 12:50:58 PM
Here is how to know the path of a module
import importlib
from pathlib import Path
# The name of the module you're interested in
module_name = "module-x"
# Dynamically import the module using its name
module = importlib.import_module(module_name)
# Get the path to the module's file
module_path = Path(module.__file__)
print(f"The path to {module_name} is: {module_path}")
satya - 3/15/2024, 3:52:18 PM
multiple args
def pathjoin_segments(seg1: str, *pathSegments: str):
return os.path.join(seg1, *pathSegments)
satya - 3/17/2024, 10:41:40 AM
working with datetime objects
from datetime import date, datetime
# For the date 2024-03-17
date_object = date(2024, 3, 17)
# For the datetime 2022-01-01 at 10:00:00
datetime_object1 = datetime(2022, 1, 1, 10, 0, 0)
# For the datetime 2022-01-01 at 14:00:00
datetime_object2 = datetime(2022, 1, 1, 14, 0, 0)
# Print the objects to verify
print(date_object)
print(datetime_object1)
print(datetime_object2)