Skip to content

Instantly share code, notes, and snippets.

@jymchng
Last active December 11, 2024 17:40
Show Gist options
  • Save jymchng/40918a5bf0cfc7f10845d22bc13513d2 to your computer and use it in GitHub Desktop.
Save jymchng/40918a5bf0cfc7f10845d22bc13513d2 to your computer and use it in GitHub Desktop.
testing play-python.asyncmove.com from gist

Testing Gist for New Feature on the Playground

Notes

  1. requirements.txt can only hold newline separated package names with comments on each new line, e.g.
pandas
# comment
pydantic
# not allowed: `pydantic==2.1.1`
  1. readme.md MUST be named strictly in small letters, i.e. exactly readme.md for it to be displayed on the markdown editor on the right panel.
import os, sys # Possible to import most packages; go to [Installed Packages] tab, type in the names
# delimited by comma of the packages you want to install.
# Click on [Add Package(s)]
# Then import those packages, e.g. import attrs
import logging
from logging import getLogger
logger = getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', stream=sys.stdout)
# Click on the dropdown button and choose [Format], then click on the [Format] button
# to see how the `fibonacci` function definition is reformatted.
# Define a function that takes an integer n and returns the nth number in the Fibonacci
# sequence.
def fibonacci(n):
"""Compute the nth number in the Fibonacci sequence."""
x = 1
if n == 0: return 0
elif n == 1: return 1
else: return fibonacci(n - 1) + fibonacci(n - 2)
# Use a for loop to generate and print the first 10 numbers in the Fibonacci sequence.
for i in range(10):
print(fibonacci(i))
logger.info(f"`fibonacci({i})` = {fibonacci(i)}")
# Click on the dropdown button and choose [Test], then click on the [Test] button
# to see how you can use pytest on this playground.
def test_fibonacci():
for i in range(10):
assert fibonacci(i) == fibonacci(i)
attrs
numpy
pandas
# can have comments
pydantic
# but no version allowed, e.g. `pydantic==2.1.1` not allowed
pytest
from weakref import WeakValueDictionary
import pytest
class GenericWrappedBoundedInt(int):
MAX_VALUE: int = 0
__concrete_bounded_ints__ = WeakValueDictionary()
def __new__(self, value: int):
inst = super().__new__(self, value % self.MAX_VALUE)
return inst
def __repr__(self) -> str:
return f"<BoundedInt[MAX_VALUE={self.MAX_VALUE}]: {super().__repr__()}>"
def __str__(self) -> str:
return repr(self)
def __class_getitem__(cls, idx=MAX_VALUE):
if not isinstance(idx, int):
raise TypeError(f"cannot make `BoundedInt[{idx}]`")
if idx not in cls.__concrete_bounded_ints__:
class ConcreteBoundedInt(cls):
MAX_VALUE = idx
cls.__concrete_bounded_ints__[idx] = ConcreteBoundedInt
return cls.__concrete_bounded_ints__[idx]
# here you got to write many operator overrides: +, -, etc.
def test_bounded_int():
bounded_twenty_int_value = GenericWrappedBoundedInt[20](11)
bounded_twenty_int_value += 10 # return type here is int
with pytest.raises(AssertionError):
assert bounded_twenty_int_value == (11 + 10) % 20 # (11 + 10 = 21) % 20 = 1
assert bounded_twenty_int_value == 21 # 11 + 10 = 21
assert isinstance(bounded_twenty_int_value, int)
assert not isinstance(bounded_twenty_int_value, GenericWrappedBoundedInt[20])
bounded_twenty_int_value -= 22
with pytest.raises(AssertionError):
assert bounded_twenty_int_value == (21 - 22) % 20 # (21 - 22 = -1) % 20 = 19
assert bounded_twenty_int_value == -1 # 21 - 22 = -1
assert isinstance(bounded_twenty_int_value, int)
assert not isinstance(bounded_twenty_int_value, GenericWrappedBoundedInt[20])
def benchmark():
import time
bounded_twenty_int_value = GenericWrappedBoundedInt[20](11)
start_time = time.time()
for _ in range(100_000):
bounded_twenty_int_value += 10
end_time = time.time()
print(f"Benchmark completed in {end_time - start_time:.50f} seconds")
print(f"Final value: {bounded_twenty_int_value}")
if __name__ == '__main__':
benchmark()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment