Skip to content

Commit

Permalink
updating examples
Browse files Browse the repository at this point in the history
  • Loading branch information
plockaby committed Sep 14, 2024
1 parent 42020d1 commit 01a08dc
Show file tree
Hide file tree
Showing 78 changed files with 1,663 additions and 1,585 deletions.
6 changes: 2 additions & 4 deletions source/examples/async/async_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import asyncio
import time
import datetime
import random


Expand All @@ -20,16 +19,15 @@ async def small_task(num):
# pause for a random amount of time between 0 and 2 seconds
await asyncio.sleep(random.random() * 2)


async def slow_task():
while True: # keep going forever
print("running the slow task- blocking!")
# This will block for 2-10 seconds!
# result = slow_function(random.random() * 8 + 2)
# uncomment to put it on a different thread:
# result = slow_function(random.random() * 8 + 2)
result = await loop.run_in_executor(None,
slow_function,
random.random() * 8 + 2)
result = await loop.run_in_executor(None, slow_function, random.random() * 8 + 2)
print("slow function done: result", result)
# await asyncio.sleep(0.0) # to release the loop

Expand Down
1 change: 1 addition & 0 deletions source/examples/async/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import asyncio
import aiohttp


async def get_events():
async with aiohttp.ClientSession() as session:
print("created a session")
Expand Down
2 changes: 2 additions & 0 deletions source/examples/async/gather.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ async def factorial(name, number):
f *= i
print("Task %s: factorial(%s) = %s" % (name, number, f))


async def run():
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)


asyncio.run(run())
2 changes: 0 additions & 2 deletions source/examples/async/get_news.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


NEWS_API_KEY = 1fabc23bb9bc485ca59b3966cbd6ea26

url = https://newsapi.org/
1 change: 1 addition & 0 deletions source/examples/async/get_news_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import time
import requests


WORD = "trump"

NEWS_API_KEY = "84d0483394c44f288965d7b366e54a74"
Expand Down
13 changes: 12 additions & 1 deletion source/examples/async/just_coroutines.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
Hopefully, this will help us better understand how they work.
"""


async def corout():
print("running corout")
return "something returned"


# Note that the returned value gets tacked on to the StopIteration

async def corout2():
Expand All @@ -34,6 +36,7 @@ async def corout2():
"""applying the coroutine decorator makes a generator a coroutine, and thus an awaitable object.
"""


@coroutine
def do_nothing():
"""
Expand All @@ -51,6 +54,7 @@ def do_nothing():
# """But we can now we can make another coroutine that awaits on the first one:
# """


async def do_a_few_things(num=3):
# a loop for multiple things
for i in range(num):
Expand Down Expand Up @@ -113,6 +117,7 @@ async def do_a_few_things(num=3):

print("\n\n*********\n\n")


@coroutine
def nothing():
"""
Expand All @@ -122,6 +127,7 @@ def nothing():
yield "from nothing"
return ("returned from nothing")


@coroutine
def count(num):
"""
Expand All @@ -132,13 +138,15 @@ def count(num):
for i in range(num):
yield f"count: {i}"


async def do_a_few_things(num=3, name="no_name"):
# a loop for multiple things
for i in range(num):
print(f'\nin the "{name}" loop for the {i}th time')
from_await = await nothing()
print("value returned from await:", from_await)


# create it:
daft = do_a_few_things(5, "first one")

Expand Down Expand Up @@ -187,6 +195,7 @@ def count(num):
yield f"count: {i}"
return "returned from count"


# and this one loops a bit more, calling count
async def do_a_few_things(num=3, name="no_name"):
# a loop for multiple things
Expand All @@ -195,6 +204,7 @@ async def do_a_few_things(num=3, name="no_name"):
from_await = await count(i + 2)
print("value returned from await:", from_await)


# """
# We're going to create a little class to make a task loop
# """
Expand Down Expand Up @@ -278,7 +288,7 @@ def sleep(secs=0):

async def fib(n):
"""
Classic fibbonacci number, but with a delay
Classic fibonacci number, but with a delay
"""
if n == 0:
return 0
Expand Down Expand Up @@ -333,6 +343,7 @@ def run_all(self):
results.append(si.args[0])
return results


# """
# Now let's try it out by putting a creating a few tasks and putting them on the loop.
# """
Expand Down
4 changes: 3 additions & 1 deletion source/examples/classes/simple_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def __init__(self, x, y):
self.x = x
self.y = y


p2 = Point2(4, 5)
print(p2.size)
print(p2.color)
Expand All @@ -49,8 +50,8 @@ def get_color(self):
def get_size(self):
return self.size

class Rect:

class Rect:
def __init__(self, w, h):
self.w = w
self.h = h
Expand Down Expand Up @@ -93,6 +94,7 @@ def grow(self, factor=2):
"""grows the area by factor..."""
self.diameter = self.diameter * math.sqrt(2)


nc = NewCircle
print(nc.color)

Expand Down
3 changes: 3 additions & 0 deletions source/examples/closures_currying/play_with_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
some example code to play with scope
"""


def start_at(x):
def increment_by(y):
return x + y
return increment_by


closure_1 = start_at(3)
closure_2 = start_at(5)
closure_1(2)
Expand All @@ -15,6 +17,7 @@ def increment_by(y):

def make_um_counter():
series = []

def um_counter(new_word):
series.append(new_word) # free variable
count = 0
Expand Down
3 changes: 2 additions & 1 deletion source/examples/context_managers/looking_glass.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import sys
import contextlib


class LookingGlass:

def __enter__(self):
Expand All @@ -22,11 +23,11 @@ def __exit__(self, exc_type, exc_value, traceback):
return True



@contextlib.contextmanager
def looking_glass():
msg = ''
original_write = sys.stdout.write

def reverse_write(text):
original_write(text[::-1])

Expand Down
2 changes: 1 addition & 1 deletion source/examples/context_managers/raising_an_assert.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ def test_raise_assertion():
raise AssertionError("this was done with a direct raise")


def test_trasditional_assert():
def test_traditional_assert():
assert False, "this was done with a forced assert"
3 changes: 3 additions & 0 deletions source/examples/decorators/play_with_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

def my_decorator(func):
print('in my_decorator for: ', func.__name__)

def inner():
print('in inner function')
func()
Expand All @@ -14,10 +15,12 @@ def inner():
def first_func():
print('running first_func')


@my_decorator
def other_func():
print('running other_func')


print('imports and loading done')

if __name__ == '__main__':
Expand Down
12 changes: 6 additions & 6 deletions source/examples/iterators_generators/my_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""


l = [1,2,3,4,5,]
x = [1, 2, 3, 4, 5,]


def my_for(an_iterable, func):
Expand All @@ -16,13 +16,13 @@ def my_for(an_iterable, func):
func() will be called with each item in an_iterable
:param an_iterable: anything that satisfies the interation protocol
:param an_iterable: anything that satisfies the iteration protocol
:param func: a callable -- it will be called, passing in each item
in an_iterable.
"""
# equiv of "for i in l:"
# equiv of "for i in x:"
iterator = iter(an_iterable)
while True:
try:
Expand All @@ -37,9 +37,9 @@ def my_for(an_iterable, func):
def print_func(x):
print(x)

l = [1,2,3,4,5,]
my_for(l, print_func)
x = [1, 2, 3, 4, 5,]
my_for(x, print_func)

t = ('a','b','c','d')
t = ('a', 'b', 'c', 'd')

my_for(t, print_func)
2 changes: 2 additions & 0 deletions source/examples/iterators_generators/yield_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def counter():
print('counter: yield', i)
yield i


def y_range(start, stop, step=1):
print("at the start")
i = start
Expand All @@ -16,6 +17,7 @@ def y_range(start, stop, step=1):
i += step
print("at end of func")


def test():
yield 4
yield 45
Expand Down
3 changes: 2 additions & 1 deletion source/examples/metaprogramming/singleton.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3

"""
example of using __metaclass__ to impliment the singleton pattern
example of using __metaclass__ to implement the singleton pattern
"""


Expand All @@ -17,6 +17,7 @@ def __call__(cls, *args, **kwargs):
class MyClass(metaclass=Singleton):
pass


object1 = MyClass()
object2 = MyClass()

Expand Down
1 change: 1 addition & 0 deletions source/examples/modules/my_package/a_module.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
name3 = "Mary"
name4 = "Jane"


def a_function():
print("a_function has been called")
1 change: 1 addition & 0 deletions source/examples/multiple_inheritance/mro.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def my_method(self):
print("called D")
super(D, self).my_method()


print(D.mro())
d = D()
print(d.my_method())
6 changes: 3 additions & 3 deletions source/examples/multiple_inheritance/object_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
wxPython desktop GUI library
FloatCanvas is a system for handling zoomable and scalable graphics in
a object-persistant way. That is, graphic objects like circles and
a object-persistent way. That is, graphic objects like circles and
rectangles and what not can be created ahead of time, and then the Canvas
can render them accoding to the current zoom level and pan position, etc.
can render them according to the current zoom level and pan position, etc.
This lets the user think about their graphics object should look like,
and not have to worry about exactly how to draw them -- or their pixel
Expand Down Expand Up @@ -54,7 +54,7 @@ def __init__(self,
self.background = background

def add_object(self, draw_object, position="top"):
#fixme: maybe overload the inplace addition operator?
# fixme: maybe overload the inplace addition operator?
"""
Add a new object to the canvas.
Expand Down
Loading

0 comments on commit 01a08dc

Please sign in to comment.