Python Journal 2, 2024

3.7.4


c:\satya\i\python374

Python home

3.12


# 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']

stack = ['a', 'b', 'c', 'd']

for item in reversed(stack):
    print(item)

Previous version of the journal: Essential Python

Python peculiarities

vscode folder

Setting type hints for python in vscode


from typing import Any, cast

any_value: Any = get_some_value()  # This could be anything
str_value: str = cast(str, any_value)

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")

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)

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

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

class ISingleton():
    @staticmethod
    def isSingleton(classObj: Type[Any]) -> bool:
        return issubclass(classObj,ISingleton)

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)

@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)

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}")

def pathjoin_segments(seg1: str, *pathSegments: str):
    return os.path.join(seg1, *pathSegments)

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)