Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mahabubx7/evented-thing-py
https://github.com/mahabubx7/evented-thing-py
Last synced: 1 day ago
JSON representation
- Host: GitHub
- URL: https://github.com/mahabubx7/evented-thing-py
- Owner: mahabubx7
- Created: 2024-03-23T06:15:14.000Z (8 months ago)
- Default Branch: main
- Last Pushed: 2024-03-23T06:19:18.000Z (8 months ago)
- Last Synced: 2024-03-23T07:27:48.987Z (8 months ago)
- Language: Python
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Evented Thing | Python
### Source Code | Solution
```python
class EventedThing:
def __init__(self) -> None:
self.events = {} # storage hashmap for eventsdef on(self, event: str, callback: callable) -> None:
if event in self.events: # Check if event already exists
self.events[event].append(callback) # Append callback to the event
else:
self.events[event] = [callback] # Create a new event with the callbackdef trigger(self, event: str, *args) -> None:
if event in self.events: # Check if event exists
for callback in self.events[event]: # Loop through all callbacks
callback(*args) # Call the callback with arguments
```### Sample Test Cases
```python
import unittest # using unit-test lib# Test suit with its test cases
class TestEventedThing(unittest.TestCase):
def test_on(self) -> None:
event = EventedThing()
def callback():
print("Event Triggered!")
event.on("click", callback)
self.assertEqual(event.events, {"click": [callback]})def test_trigger(self) -> None:
event = EventedThing()
count = 0
def callback():
nonlocal count
count += 1
event.on("click", callback)
event.trigger("click")
print(count)
self.assertEqual(count, 1)def test_meet_event(self):
passed_args = []
event = EventedThing()
def callback(*args):
nonlocal passed_args
passed_args = list(args)
event.on('meet', callback)
# Triggering 'meet' event with one argument
event.trigger('meet', 'arg1')
self.assertEqual(passed_args, ['arg1'])
# Triggering 'meet' event with two arguments
event.trigger('meet', 'arg1', 'arg2')
self.assertEqual(passed_args, ['arg1', 'arg2'])if __name__ == "__main__":
unittest.main()
```