Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 132485
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T06:16:12+00:00 2026-05-11T06:16:12+00:00

In Python, I’ve seen the recommendation to use holding or wrapping to extend the

  • 0

In Python, I’ve seen the recommendation to use holding or wrapping to extend the functionality of an object or class, rather than inheritance. In particular, I think that Alex Martelli spoke about this in his Python Design Patterns talk. I’ve seen this pattern used in libraries for dependency injection, like pycontainer.

One problem that I’ve run into is that when I have to interface with code that uses the isinstance anti-pattern, this pattern fails because the holding/wrapping object fails the isinstance test. How can I set up the holding/wrapping object to get around unnecessary type checking? Can this be done generically? In some sense, I need something for class instances analogous to signature-preserving function decorators (e.g., simple_decorator or Michele Simionato’s decorator).

A qualification: I’m not asserting that all isinstance usage is inappropriate; several answers make good points about this. That said, it should be recognized that isinstance usage poses significant limitations on object interactions—it forces inheritance to be the source of polymorphism, rather than behavior.

There seems to be some confusion about exactly how/why this is a problem, so let me provide a simple example (broadly lifted from pycontainer). Let’s say we have a class Foo, as well as a FooFactory. For the sake of the example, assume we want to be able to instantiate Foo objects that log every function call, or don’t—think AOP. Further, we want to do this without modifying the Foo class/source in any way (e.g., we may actually be implementing a generic factory that can add logging ability to any class instance on the fly). A first stab at this might be:

class Foo(object):     def bar():         print 'We\'re out of Red Leicester.'  class LogWrapped(object):     def __init__(self, wrapped):         self.wrapped = wrapped     def __getattr__(self, name):         attr = getattr(self.wrapped, name)         if not callable(attr):             return attr         else:             def fun(*args, **kwargs):                 print 'Calling ', name                 attr(*args, **kwargs)                 print 'Called ', name             return fun  class FooFactory(object):     def get_foo(with_logging = False):         if not with_logging:             return Foo()         else:             return LogWrapped(Foo())  foo_fact = FooFactory() my_foo = foo_fact.get_foo(True) isinstance(my_foo, Foo) # False! 

There are may reasons why you might want to do things exactly this way (use decorators instead, etc.) but keep in mind:

  • We don’t want to touch the Foo class. Assume we’re writing framework code that could be used by clients we don’t know about yet.
  • The point is to return an object that is essentially a Foo, but with added functionality. It should appear to be a Foo—as much as possible—to any other client code expecting a Foo. Hence the desire to work around isinstance.
  • Yes, I know that I don’t need the factory class (preemptively defending myself here).
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T06:16:13+00:00Added an answer on May 11, 2026 at 6:16 am

    If the library code you depend on uses isinstance and relies on inheritance why not follow this route? If you cannot change the library then it is probably best to stay consistend with it.

    I also think that there are legitimate uses for isinstance, and with the introduction of abstract base classes in 2.6 this has been officially acknowledged. There are situations where isinstance really is the right solution, as opposed to duck typing with hasattr or using exceptions.

    Some dirty options if for some reason you really don’t want to use inheritance:

    • You could modify only the class instances by using instance methods. With new.instancemethod you create the wrapper methods for your instance, which then calls the original method defined in the original class. This seems to be the only option which neither modifies the original class nor defines new classes.

    If you can modify the class at runtime there are many options:

    • Use a runtime mixin, i.e. just add a class to the __base__ attribute of your class. But this is more used for adding specific functionality, not for indiscriminate wrapping where you don’t know what need to be wrapped.

    • The options in Dave’s answer (class decorators in Python >= 2.6 or Metaclasses).

    Edit: For your specific example I guess only the first option works. But I would still consider the alternative of creating a LogFoo or chosing an altogether different solution for something specific like logging.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 89k
  • Answers 89k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer start it for all users always but check a configuration… May 11, 2026 at 5:52 pm
  • Editorial Team
    Editorial Team added an answer Check out NSInvocation, which lets you "performSelector" in a much… May 11, 2026 at 5:52 pm
  • Editorial Team
    Editorial Team added an answer ChrisV- see this post. Also it easier for people to… May 11, 2026 at 5:51 pm

Related Questions

In Python, I want to make selected instance attributes of a class be readonly
In Python, I can do: list = ['a', 'b', 'c'] ', '.join(list) # 'a,
In Python, I've got a list of dictionaries that looks like this: matchings =
In Python, I can compile a regular expression to be case-insensitive using re.compile :
In python, I can do something like this: List=[3, 4] def Add(x, y): return

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.