mirror of
				https://github.com/Brandon-Rozek/website.git
				synced 2025-10-31 05:41:13 +00:00 
			
		
		
		
	Added Type annotations
This commit is contained in:
		
							parent
							
								
									49397eebfd
								
							
						
					
					
						commit
						f8d002207d
					
				
					 1 changed files with 7 additions and 6 deletions
				
			
		|  | @ -12,10 +12,11 @@ It is common for larger applications to have modules that publishes and subscrib | ||||||
| First let us concern ourselves with a single event since that's the easiest. Here we will create an application class that stores callbacks of functions through the subscribe decorator. Calling `emit` will send a message to all the functions stored in `self.callbacks`. | First let us concern ourselves with a single event since that's the easiest. Here we will create an application class that stores callbacks of functions through the subscribe decorator. Calling `emit` will send a message to all the functions stored in `self.callbacks`. | ||||||
| 
 | 
 | ||||||
| ```python | ```python | ||||||
|  | from typing import Callable, List | ||||||
| class Application: | class Application: | ||||||
|     def __init__(self): |     def __init__(self): | ||||||
|         self.callbacks = [] |         self.callbacks: List[Callable] = [] | ||||||
|     def subscribe(self, func): |     def subscribe(self, func: Callable): | ||||||
|         if not callable(func): |         if not callable(func): | ||||||
|             raise ValueError("Argument func must be callable.") |             raise ValueError("Argument func must be callable.") | ||||||
|         self.callbacks.append(func) |         self.callbacks.append(func) | ||||||
|  | @ -53,12 +54,12 @@ Let's say you want the application to handle different types of events. Now `sel | ||||||
| 
 | 
 | ||||||
| ```python | ```python | ||||||
| from collections import defaultdict | from collections import defaultdict | ||||||
| 
 | from typing import Callable, Optional | ||||||
| class Application: | class Application: | ||||||
|     def __init__(self): |     def __init__(self): | ||||||
|         self.callbacks = defaultdict(list) |         self.callbacks: Dict[str, List[Callable]] = defaultdict(list) | ||||||
|     def on(self, event, func=None): |     def on(self, event: str, func: Optional[Callable] = None): | ||||||
|         def subscribe(func): |         def subscribe(func: Callable): | ||||||
|             if not callable(func): |             if not callable(func): | ||||||
|                 raise ValueError("Argument func must be callable.") |                 raise ValueError("Argument func must be callable.") | ||||||
|             self.callbacks[event].append(func) |             self.callbacks[event].append(func) | ||||||
|  |  | ||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue