python-patterns | A collection of design patterns/idioms in Python | Architecture library
kandi X-RAY | python-patterns Summary
Support
Quality
Security
License
Reuse
- Start the CPU
- Jump to the given position
- Freeze the processor
- Print the product list
- List of all available products
- Wrapper for template functions
- Save changes to save
- Check if a request is in the db
- Get interval from database
- Show information about an item
- Capitalize a string
- Dispatch request
- Dispatch the given request
- Show price information for a given product
- Return information about a specific product
- Switchover state
- Commit all target states
- Unsubscribes a subscriber
- Sends a message
- Return the number of two values
- Set new data
- Set self value to self
- Perform a switchover
- Invoked when an operator is received
- Calls the fault trigger
- Counts a number of items to 5
python-patterns Key Features
python-patterns Examples and Code Snippets
import types class StrategyExample: def __init__(self, func=None): self.name = 'Strategy Example 0' if func is not None: self.execute = types.MethodType(func, self) # <1> def execute(self): print(self.name) def execute_replacement1(self): print(self.name + ' from execute 1') def execute_replacement2(self): print(self.name + ' from execute 2') if __name__ == '__main__': strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1) strat1.name = 'Strategy Example 1' strat2 = StrategyExample(execute_replacement2) strat2.name = 'Strategy Example 2' strat0.execute() strat1.execute() strat2.execute()
class TaskStrategy: def __init__(self, func=None, event=None): self.name = func.__name__ if func else "default" self.event = event if func: self.execute = types.MethodType(func, self) print('{} class , task {}'.format(self.__class__.__name__, self.name)) def execute(self): pass def reply_message(self, obj): line_bot_api.reply_message(self.event.reply_token, obj) class TemplateStrategy(TaskStrategy): def execute(self): ...... self.reply_message(carousel_template_message) class ImageStrategy(TaskStrategy): def execute(self): ...... self.reply_message(sticker_message)
def apple_news(self): task = AppleNews('https://tw.appledaily.com/new/realtime') self.reply_message(TextSendMessage(text=task.parser()))
class Bot: # <1> task_map = { MyDict.eyny_movie: eyny_movie, ..... } # <2> template_map = { MyDict.start_template: start_template, ..... } def __init__(self, val): self.val = val self.special_handle() def strategy_action(self): # <3> strategy_class = None action_fun = None if self.val in self.task_map: strategy_class = TaskStrategy action_fun = self.task_map.get(self.val) elif self.val in self.template_map: strategy_class = TemplateStrategy action_fun = self.template_map.get(self.val) return strategy_class, action_fun def special_handle(self): if self.val.lower() == MyDict.eyny_movie: self.val = self.val.lower()
@handler.add(MessageEvent, message=TextMessage) def handle_message(event): message = event.message.text bot = Bot(message) strategy_class, action_fun = bot.strategy_action() # <1> if strategy_class: # <2> task = strategy_class(action_fun, event) task.name = str(action_fun) task.execute() return 0 default_task = TemplateStrategy(event=event) # <3> default_task.execute()
Y. Kashu, Recreation of Nature - Computational Simulation of Emergent Phenomenon and Cognitive Process in Nature, 2019, GitHub repository, https://github.com/Kashu7100/Recreation-of-Nature
@misc{recreation_of_nature, author = {Kashu Yamazaki}, title = {{R}ecreation of Nature}, year = {2019}, publisher = {GitHub}, journal = {GitHub repository}, keywords = {Python, Simulation, Emergent phenomenon, Cognitive process} howpublished = {\url{https://github.com/Kashu7100/Recreation-of-Nature}}, }
Trending Discussions on python-patterns
Trending Discussions on python-patterns
QUESTION
I have been trying to figure out when and where to use different patterns in Python. I came across this document: https://python-patterns.guide/gang-of-four/abstract-factory/
Now this made me wonder how can I do what he says in my code. Here is my implementation is an abstract factory. Not sure if its correct.
from abc import abstractmethod, ABC
from sqlalchemy.orm import Session
from managers.database_manager import DatabaseManager
from managers.log_manager import LogManager
from managers.sqlalchemy_manager import get_db
from models.bal.post import Post
from models.dal.models import Post as ORMPost
class PostsManager(ABC):
def __init__(self):
pass
@abstractmethod
def get_posts(self):
pass
@abstractmethod
def get_post(self, post_id):
pass
@abstractmethod
def create_post(self, post: Post):
pass
@abstractmethod
def delete_post(self, post_id):
pass
@abstractmethod
def update_post(self, post_id, post: Post):
pass
class PostsManagerFactory:
@staticmethod
def get_posts_manager(use_orm=True) -> PostsManager:
if use_orm:
return PostsManagerWithORM()
else:
return PostsManagerWithoutORM()
class PostsManagerWithORM(PostsManager):
def get_posts(self):
db: Session = get_db()
posts = db.query(ORMPost).all()
return posts
def get_post(self, post_id):
pass
def create_post(self, post: Post):
pass
def delete_post(self, post_id):
pass
def update_post(self, post_id, post: Post):
pass
class PostsManagerWithoutORM(PostsManager):
def __init__(self):
super().__init__()
self.db_manager = DatabaseManager()
def get_posts(self):
posts = self.db_manager.execute_query("select * from posts")
return posts
def get_post(self, post_id):
post = self.db_manager.execute_query("SELECT * FROM posts WHERE id='%s'", (post_id,), single_record_flag=True)
return post
def create_post(self, post: Post):
post = self.db_manager.execute_query("INSERT INTO posts (title, content) VALUES (%s, %s) RETURNING *",
(post.title, post.content), single_record_flag=True)
return post
def delete_post(self, post_id):
post = self.db_manager.execute_query("DELETE FROM posts WHERE id = %s RETURNING *", (post_id,),
single_record_flag=True)
return post
def update_post(self, post_id, post: Post):
post = self.db_manager.execute_query(
"UPDATE posts SET title = %s, content = %s, published = %s WHERE id= %s RETURNING *",
(post.title, post.content, post.published, post_id),
single_record_flag=True)
return post
Here is how I am calling these methods:
posts_manager = PostsManagerFactory.get_posts_manager()
posts = posts_manager.get_posts()
My first question, is it the right way to use abstract factory pattern? If, not please let me know, I will probably ask a new question. Anyway if it is, why does that document say about using callables is better than using abstract factory pattern, how do I do that in this case?
ANSWER
Answered 2021-Nov-14 at 06:32Following you last comment.
I would not use abstract factory pattern for this use case. May I ask why you want to use it ?
When I suggest to remove the PostsManagerFactory
class by extracting the get_posts_manager
to a function, I mean replacing this code snippet
class PostsManagerFactory:
@staticmethod
def get_posts_manager(use_orm=True) -> PostsManager:
if use_orm:
return PostsManagerWithORM()
else:
return PostsManagerWithoutORM()
with this
def get_posts_manager(use_orm=True) -> PostsManager:
if use_orm:
return PostsManagerWithORM()
else:
return PostsManagerWithoutORM()
that you may want to shorten this way
def get_posts_manager(use_orm=True) -> PostsManager:
return PostsManagerWithORM() if use_orm else PostsManagerWithoutORM()
Then, you could use it in your code simply by calling the function
posts_manager = get_posts_manager() # <----
posts = posts_manager.get_posts()
QUESTION
Consider the following class hierarchy:
A
|
_____________
| | |
Foo Bar Baz
The class A
defines a __call__
method, which Foo
, Bar
and Baz
implement. The classes also define various other methods I'm interested in. All three classes come from a third party library, so I do not want to change their implementation. However, in some cases at runtime, I would like to alter the implementation of Foo
's, Bar
's and Baz
' __call__
method. Right now, I did this by defining my own classes, which solely override the __call__
method:
Foo Bar Baz
| | |
Foo1 Bar1 Baz1
Then, depending on the situation, I instantiate the desired class to a common variable. I'm not satisfied with this solution, as it has the following drawbacks:
The additions I make to
__call__
are not necessarily uniquely determined by the class.Bar1
andBaz1
might share the implementation of__call__
(butBar
andBaz
differ in other aspects). So, as far as I understand, I need to repeat code.At runtime, instantiating the desired class requires m × n case distinctions (where m is the number of classes at the level of
Foo
,Bar
, andBaz
and n is the number of classes at the level ofFoo1
,Bar1
, andBaz1
). This will grow rapidly as m or n increase. Ideally, I would like the number of case distinction to be m + n.
I already had a look at https://python-patterns.guide/gang-of-four/composition-over-inheritance/#solution-3-the-decorator-pattern, at Cannot overwrite implementation for __call__ and at __call__ method of type class. However, these solutions do not fit perfectly to my case, as (1) I'm overriding a dunder method (2) of third party classes and (3) still would like to have access to the other class methods of Foo
, Bar
, and Baz
.
Is there an elegant why to achieve what I am looking for?
Edit: The change of __call__
at runtime should only affect the instance object, not the class or all objects of that class at once.
Edit 2 (requested by @enzo):
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class A(metaclass=ABCMeta):
@abstractmethod
def __call__(self, x, y):
"""Docstring A"""
@abstractmethod
def method1(self, a, b):
"""Docstring method1"""
class Foo(A):
def __call__(self, x, y):
return x + y # indeed, no dependence on `self`
def method1(self, a, b):
# but this might depend on `self`
pass
class Bar(A):
def __call__(self, x, y):
return x * y # indeed, no dependence on `self`
def method1(self, a, b):
# but this might depend on `self`
pass
def method2(self, c, d):
# but this might depend on `self`
pass
class Baz(A):
def __call__(self, x, y):
return x ** y # indeed, no dependence on `self`
def method1(self, a, b):
# but this might depend on `self`
pass
def method2(self, c, d):
# but this might depend on `self`
pass
ANSWER
Answered 2021-Jul-30 at 08:48you can inject a custom call into it:
class A():
def __call__(self, *args, **kwargs):
print("In A.__call__")
def showCall(self):
print(self.__call__)
class foo(A):
pass
class bar(A):
pass
class baz(A):
pass
def my_custom_func():
print("In my custom func")
f = foo()
f()
b = bar()
b()
f.showCall()
b.showCall()
print("##setting call##")
f.__call__ = my_custom_func
print("##running f calls##")
f.showCall()
f()
print("##running b calls##")
b.showCall()
b()
While this does solve your injection problem other things might come into play where you still need the original __call__
method. In which case you will need to save them before setting them.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install python-patterns
You can use python-patterns like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page