> > pydemo
Threads
python3 ( 495357 ) - python3 ( 495357 ) stack: <module>(pydemo:7)
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
from abc import ABC, abstractmethod
import threading

lock = threading.Lock()

class SharedResourceWithLock:
    def __init__(self):
        self.counter = 0
        print(f"SharedResourceWithLock __init__ self.counter: {self.counter}")

    def increment(self):
        with lock:
            print(f"Thread {threading.current_thread().name} acquiring lock")
            self.counter += 1
            print(f"Thread {threading.current_thread().name} released lock, counter = {self.counter}")

def task_with_lock(resource):
    for _ in range(3):
        resource.increment()

rlock = threading.RLock()

class SharedResourceWithRLock:
    def __init__(self):
        self.counter = 0

    def increment(self):
        with rlock:
            self.counter += 1
            self.double_increment()

    def double_increment(self):
        with rlock:
            self.counter += 1

def task_with_rlock(resource):
    resource.increment()

condition = threading.Condition()

class SharedResourceWithCondition:
    def __init__(self):
        self.ready = False

    def produce(self):
        with condition:
            print("Producing item..."); self.ready = True; condition.notify()

    def consume(self):
        with condition:
            while not self.ready:
                condition.wait()
            print("Consuming item...")

def task_with_condition():
    resource = SharedResourceWithCondition()
    producer = threading.Thread(target=resource.produce)
    consumer = threading.Thread(target=resource.consume)

    consumer.start()
    producer.start()

    producer.join()
    consumer.join()

def func1(msg="hello"):
    print("print in func1"); print("hi by print in func1")
    if msg != "hello":
        return msg
    else:
        return "hello"

def func2():
    print("print in func2"); func1(); func1("say")

def func3():
    print("print in func3"); func2()

def func4():
    print("print in func4")
    func3()

"""Decorator"""
def loop_decorator(func):
    def wrapper(*args, **kwargs):
        print("Starting the loop...")
        func(*args, **kwargs)
        print("Loop ended.")
    return wrapper

@loop_decorator
def my_while_loop():
    count = 0
    while count < 5:
        print(count)
        count += 1

def decorator_one(func):
    def wrapper():
        print("Decorator One Applied")
        func()
    return wrapper

def decorator_two(func):
    def wrapper():
        print("Decorator Two Applied")
        func()
    return wrapper

@decorator_one
@decorator_two # The order of applying decorators is from the innermost to the outermost, with the decorator closest to the function or class definition being applied first.
def my_function():
    print("Hello from my_function!")

def main():
    print("print in main")
    func4()

    my_function()

    # Python Syntax and Data Structure Examples

    # 1. Basic data types and variables
    a = 10  # Integer
    b = 3.14  # Float
    s = "Hello, World!"  # String
    lst = [1, 2, 3, 4, 5]  # List
    tpl = (1, 2, 3)  # Tuple
    dct = {'name': 'Alice', 'age': 25}  # Dictionary
    st = {1, 2, 3, 4}  # Set

    print(f"Integer: {a}, Float: {b}, String: {s}")

    # 2. Conditional statements
    if a > 5:
        print("a is greater than 5")
    elif a == 5:
        print("a is equal to 5")
    else:
        print("a is less than 5")

    print("ok") if 1 == 1 else print("this will not happen") # value_if_true if condition else value_if_false

    http_status = 200
    match http_status:
        case 200:
            print("OK")
        case 404:
            print("Not Found")
        case 500:
            print("Internal Server Error")
        case _:
            print("Unknown Status")

    # 3. Loop statement
    my_while_loop()

    print("List elements:")
    for item in lst:
        print(item)

    for i in range(8):
        if i == 4:
            continue
        if i % 2 == 0:
            print(f"{i} is even")
        if i == 6:
            break

    count = 0
    while count < 5:
        print(count)
        count += 1

    # 4. Function definition and multiple return values
    def calculate(x, y):
        add = x + y
        sub = x - y
        return add, sub  # Return multiple values

    sum_val, diff_val = calculate(10, 5)
    print(f"Sum: {sum_val}, Difference: {diff_val}")

    # 5. Lambda expression
    square = lambda x: x ** 2
    print(f"Square of 4: {square(4)}")

    my_lambda = lambda x: (
        print(f"Processing value: {x}"),  # expression 1
        x * 2  # expression 2: return value
    )[1]

    result = my_lambda(5)
    print(result)  # prints 10

    # 6. List comprehension
    squares = [x ** 2 for x in lst]
    print(f"List comprehension: {squares}")

    # 7. Exception handling
    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        print(f"Exception caught: {e}")
    finally:
        print("Exception handling completed")

    # Cause an exception to demonstrate automatic stderr capture
    try:
        1 / 0
    except ZeroDivisionError as e:
        sys.stderr.write(f"Caught an error: {e}\n")

    # 8. File operations
    try:
        with open("~/wpydemo.example.txt", "w") as f:
            f.write("This is a file write example.\n")
    except IOError as e:
        print(f"File operation error: {e}")

    # 9. Class and objects
    """Decorator"""
    def add_greeting(cls):
        original_method = cls.greet

        def new_greet(self):
            print("Hello! I am an Animal.")
            return original_method(self)

        cls.greet = new_greet
        return cls

    @add_greeting
    class Animal:
        def __init__(self, name):
            self.name = name

        def speak(self):
            return f"{self.name} makes a sound"

        def greet(self):
            return "Greetings from Animal!"

    class Dog(Animal):
        def speak(self):
            return f"{self.name} barks"

    dog = Dog("Buddy")
    print(dog.speak())
    print(dog.greet())

    class MyClass:
        static_variable = "Initial value"

        @classmethod
        def class_initializer(cls):
            print("Static initializer")
            cls.static_variable = "Updated value"

        def __new__(cls):
            print("Creating instance")
            return super(MyClass, cls).__new__(cls)

        def __init__(self):
            print("Initializing instance")

    obj = MyClass()
    print("obj of MyClass", obj)

    class MyAbstractClass(ABC):
        @abstractmethod
        def my_method(self):
            pass

    class ConcreteClass(MyAbstractClass):
        def my_method(self):
            print("Implemented abstract method")

    obj = ConcreteClass()
    obj.my_method()

    AnonymousClass = type('AnonymousClass', (), {'run': lambda self: print("Anonymous class")})
    obj = AnonymousClass()
    obj.run()

    # 10. Decorator function
    def logger(func):
        def wrapper(*args, **kwargs):
            print(f"Calling function: {func.__name__}")
            return func(*args, **kwargs)
        return wrapper

    @logger
    def greet(name):
        print(f"Hello, {name}")

    greet("Alice")

    # 11. Stack (using list)
    stack = []
    stack.append(1)
    stack.append(2)
    stack.append(3)
    print(f"Top of stack: {stack.pop()}")

    # 12. Queue (using list)
    queue = []
    queue.append(1)
    queue.append(2)
    queue.append(3)
    print(f"First element in queue: {queue.pop(0)}")

    # 13. Linked List (class implementation)
    class Node:
        def __init__(self, value):
            self.value = value
            self.next = None

    class LinkedList:
        def __init__(self):
            self.head = None

        def append(self, value):
            if not self.head:
                self.head = Node(value)
            else:
                current = self.head
                while current.next:
                    current = current.next
                current.next = Node(value)

        def display(self):
            current = self.head
            while current:
                print(current.value, end=" -> ")
                current = current.next
            print("None")

    ll = LinkedList()
    ll.append(1)
    ll.append(2)
    ll.append(3)
    print("Linked List: ")
    ll.display()

    # 14. Set operations
    set1 = {1, 2, 3, 4}
    set2 = {3, 4, 5, 6}
    print(f"Intersection of sets: {set1 & set2}")
    print(f"Union of sets: {set1 | set2}")

    # 15. Built-in functions map, filter, reduce
    from functools import reduce

    lst = [1, 2, 3, 4, 5]

    # map function
    squared_lst = list(map(lambda x: x ** 2, lst))
    print(f"Using map to calculate squares: {squared_lst}")

    # filter function
    even_lst = list(filter(lambda x: x % 2 == 0, lst))
    print(f"Using filter to select even numbers: {even_lst}")

    # reduce function
    sum_of_lst = reduce(lambda x, y: x + y, lst)
    print(f"Using reduce to calculate the sum: {sum_of_lst}")

    print("Before pass")
    pass  # do nothing
    print("After pass")

    # threading
    print("\n--- Lock Example ---")
    resource_with_lock = SharedResourceWithLock()
    threads = [threading.Thread(target=task_with_lock, args=(resource_with_lock,), name=f'Thread-{i}') for i in range(3)]

    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    print(f"Final counter value (Lock): {resource_with_lock.counter}")

    print("\n--- RLock Example ---")
    resource_with_rlock = SharedResourceWithRLock()
    task_with_rlock(resource_with_rlock)
    print(f"Final counter value (RLock): {resource_with_rlock.counter}")

    print("\n--- Condition Example ---")
    task_with_condition()

if __name__ == "__main__":
    main()
Variables All
No.FromNameValue
NANANANA
Output All Filter Merge
ProcessThread Filter
495357 python3 495357 python3 495363 python3 495362 python3 495361 python3 495360 python3 495359 python3
No.PNPIDTIDTNMessage
1python3495357495357python3print in main
2python3495357495357python3print in func4
3python3495357495357python3print in func3
4python3495357495357python3print in func2
5python3495357495357python3print in func1
6python3495357495357python3hi by print in func1
7python3495357495357python3print in func1
8python3495357495357python3hi by print in func1
9python3495357495357python3Decorator One Applied
10python3495357495357python3Decorator Two Applied
11python3495357495357python3Hello from my_function!
12python3495357495357python3Integer: 10, Float: 3.14, String: Hello, World!
13python3495357495357python3a is greater than 5
14python3495357495357python3ok
15python3495357495357python3OK
16python3495357495357python3Starting the loop...
17python3495357495357python30
18python3495357495357python31
19python3495357495357python32
20python3495357495357python33
21python3495357495357python34
22python3495357495357python3Loop ended.
23python3495357495357python3List elements:
24python3495357495357python31
25python3495357495357python32
26python3495357495357python33
27python3495357495357python34
28python3495357495357python35
29python3495357495357python30 is even
30python3495357495357python32 is even
31python3495357495357python36 is even
32python3495357495357python30
33python3495357495357python31
34python3495357495357python32
35python3495357495357python33
36python3495357495357python34
37python3495357495357python3Sum: 15, Difference: 5
38python3495357495357python3Square of 4: 16
39python3495357495357python3Processing value: 5
40python3495357495357python310
41python3495357495357python3List comprehension: [1, 4, 9, 16, 25]
42python3495357495357python3Exception caught: division by zero
43python3495357495357python3Exception handling completed
44python3495357495357python3Caught an error: division by zero
45python3495357495357python3File operation error: [Errno 2] No such file or directory: '~/wpydemo.example.txt'
46python3495357495357python3Buddy barks
47python3495357495357python3Hello! I am an Animal.
48python3495357495357python3Greetings from Animal!
49python3495357495357python3Creating instance
50python3495357495357python3Initializing instance
51python3495357495357python3obj of MyClass
52python3495357495357python3<__main__.main.<locals>.MyClass object at 0x7fa97893f830>
53python3495357495357python3Implemented abstract method
54python3495357495357python3Anonymous class
55python3495357495357python3Calling function: greet
56python3495357495357python3Hello, Alice
57python3495357495357python3Top of stack: 3
58python3495357495357python3First element in queue: 1
59python3495357495357python3Linked List:
60python3495357495357python31
61python3495357495357python3->
62python3495357495357python32
63python3495357495357python3->
64python3495357495357python33
65python3495357495357python3->
66python3495357495357python3None
67python3495357495357python3Intersection of sets: {3, 4}
68python3495357495357python3Union of sets: {1, 2, 3, 4, 5, 6}
69python3495357495357python3Using map to calculate squares: [1, 4, 9, 16, 25]
70python3495357495357python3Using filter to select even numbers: [2, 4]
71python3495357495357python3Using reduce to calculate the sum: 15
72python3495357495357python3Before pass
73python3495357495357python3After pass
74python3495357495357python3
75python3495357495357python3--- Lock Example ---
76python3495357495357python3SharedResourceWithLock __init__ self.counter: 0
77python3495357495361python3Thread Thread-2 acquiring lock
78python3495357495361python3Thread Thread-2 released lock, counter = 1
79python3495357495359python3Thread Thread-0 acquiring lock
80python3495357495359python3Thread Thread-0 released lock, counter = 2
81python3495357495360python3Thread Thread-1 acquiring lock
82python3495357495360python3Thread Thread-1 released lock, counter = 3
83python3495357495361python3Thread Thread-2 acquiring lock
84python3495357495361python3Thread Thread-2 released lock, counter = 4
85python3495357495359python3Thread Thread-0 acquiring lock
86python3495357495359python3Thread Thread-0 released lock, counter = 5
87python3495357495360python3Thread Thread-1 acquiring lock
88python3495357495360python3Thread Thread-1 released lock, counter = 6
89python3495357495361python3Thread Thread-2 acquiring lock
90python3495357495361python3Thread Thread-2 released lock, counter = 7
91python3495357495359python3Thread Thread-0 acquiring lock
92python3495357495359python3Thread Thread-0 released lock, counter = 8
93python3495357495360python3Thread Thread-1 acquiring lock
94python3495357495360python3Thread Thread-1 released lock, counter = 9
95python3495357495357python3Final counter value (Lock): 9
96python3495357495357python3
97python3495357495357python3--- RLock Example ---
98python3495357495357python3Final counter value (RLock): 2
99python3495357495357python3
100python3495357495357python3--- Condition Example ---
101python3495357495363python3Producing item...
102python3495357495362python3Consuming item...
END 0 0 0 00
Project:py-demo
Update:20241006
Commit:39c102b2
Source Code:pydemo
Runtime:Python3.12
System:MySystemD
Kernel:Linux5.10.211
Cpu:Intel:Corei7-7700K
Machine:AwesomeMachine