python-patterns | A collection of design patterns/idioms in Python | Architecture library

 by   faif Python Version: legacy License: No License

kandi X-RAY | python-patterns Summary

python-patterns is a Python library typically used in Architecture applications. python-patterns has no bugs, it has no vulnerabilities, it has build file available and it has medium support. You can download it from GitHub.
A collection of design patterns and idioms in Python.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        python-patterns has a medium active ecosystem.
                        summary
                        It has 36941 star(s) with 6755 fork(s). There are 1666 watchers for this library.
                        summary
                        It had no major release in the last 6 months.
                        summary
                        There are 9 open issues and 73 have been closed. On average issues are closed in 220 days. There are no pull requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of python-patterns is legacy
                        python-patterns Support
                          Best in #Architecture
                            Average in #Architecture
                            python-patterns Support
                              Best in #Architecture
                                Average in #Architecture

                                  kandi-Quality Quality

                                    summary
                                    python-patterns has 0 bugs and 0 code smells.
                                    python-patterns Quality
                                      Best in #Architecture
                                        Average in #Architecture
                                        python-patterns Quality
                                          Best in #Architecture
                                            Average in #Architecture

                                              kandi-Security Security

                                                summary
                                                python-patterns has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                python-patterns code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                python-patterns Security
                                                  Best in #Architecture
                                                    Average in #Architecture
                                                    python-patterns Security
                                                      Best in #Architecture
                                                        Average in #Architecture

                                                          kandi-License License

                                                            summary
                                                            python-patterns does not have a standard license declared.
                                                            summary
                                                            Check the repository for any license declaration and review the terms closely.
                                                            summary
                                                            Without a license, all rights are reserved, and you cannot use the library in your applications.
                                                            python-patterns License
                                                              Best in #Architecture
                                                                Average in #Architecture
                                                                python-patterns License
                                                                  Best in #Architecture
                                                                    Average in #Architecture

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        python-patterns releases are not available. You will need to build from source code and install.
                                                                        summary
                                                                        Build file is available. You can build the component from source.
                                                                        python-patterns Reuse
                                                                          Best in #Architecture
                                                                            Average in #Architecture
                                                                            python-patterns Reuse
                                                                              Best in #Architecture
                                                                                Average in #Architecture
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed python-patterns and discovered the below as its top functions. This is intended to give you an instant insight into python-patterns implemented functionality, and help decide if they suit your requirements.
                                                                                  • 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
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  python-patterns Key Features

                                                                                  A collection of design patterns/idioms in Python

                                                                                  python-patterns Examples and Code Snippets

                                                                                  line-bot-oop,說明,Strategy
                                                                                  Pythondot imgLines of Code : 98dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      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()
                                                                                  Citation
                                                                                  Pythondot imgLines of Code : 10dot imgLicense : Permissive (MIT)
                                                                                  copy iconCopy
                                                                                  
                                                                                                                      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}}, }
                                                                                  Community Discussions

                                                                                  Trending Discussions on python-patterns

                                                                                  How to use callables instead of Abstract Factory Pattern in Python?
                                                                                  chevron right
                                                                                  Overwrite __call__ method of third party class at runtime, while maintaining other methods
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  How to use callables instead of Abstract Factory Pattern in Python?
                                                                                  Asked 2021-Nov-14 at 06:32

                                                                                  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:32

                                                                                  Following 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()
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/69960168

                                                                                  QUESTION

                                                                                  Overwrite __call__ method of third party class at runtime, while maintaining other methods
                                                                                  Asked 2021-Jul-30 at 14:53

                                                                                  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 and Baz1 might share the implementation of __call__ (but Bar and Baz 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, and Baz and n is the number of classes at the level of Foo1, Bar1, and Baz1). 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:48

                                                                                  you 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.

                                                                                  Source https://stackoverflow.com/questions/68587583

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install python-patterns

                                                                                  You can download it from GitHub.
                                                                                  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

                                                                                  When an implementation is added or modified, please review the following guidelines:.
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  CLONE
                                                                                • HTTPS

                                                                                  https://github.com/faif/python-patterns.git

                                                                                • CLI

                                                                                  gh repo clone faif/python-patterns

                                                                                • sshUrl

                                                                                  git@github.com:faif/python-patterns.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Reuse Pre-built Kits with python-patterns

                                                                                  Consider Popular Architecture Libraries

                                                                                  Try Top Libraries by faif

                                                                                  shell-utils

                                                                                  by faifShell

                                                                                  system-code

                                                                                  by faifC

                                                                                  montecarlo

                                                                                  by faifPython

                                                                                  GraphNetwork

                                                                                  by faifJava

                                                                                  algo

                                                                                  by faifSwift

                                                                                  Compare Architecture Libraries with Highest Support

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit