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

  • SEARCH
  • Home
  • 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 801741
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T23:29:21+00:00 2026-05-14T23:29:21+00:00

I’m building classes where I know the intended types of the attributes, but Python

  • 0

I’m building classes where I know the intended types of the attributes, but Python of course doesn’t. While it’s un-pythonic to want to tell it, supposing I do want to, is there an idiomatic way to do so?

Why: I’m reading in foreign-format data (without type information) involving objects-nested-inside-objects. It’s easy to put it into nested dictionaries, but I want it in objects of my class-types, to get the right behaviours as well as the data. For instance: suppose my class Book has an attribute isbn which I will fill with an ISBNumber object. My data gives me the isbn as a string; I would like to be able to look at Book and say “That field should be filled by ISBNumber(theString).”

Bonus glee for me if the solution can be applied to classes I get from someone else without editing their code.

(I’m restricted to 2.6, although interested in solutions for 3.x if they exist.)

  • 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. Editorial Team
    Editorial Team
    2026-05-14T23:29:22+00:00Added an answer on May 14, 2026 at 11:29 pm

    There are many ways to achieve something like this. If coupling the input format to your object model is acceptable then you could use descriptors to create type adaptors:

    class TypeAdaptingProperty(object):
        def __init__(self, key, type_, factory=None):
            self.key = key
            self.type_ = type_
            if factory is None:
                self.factory = type_
    
        def __get__(self, instance, owner):
            if instance is None:
                return self
            return getattr(instance, self.key)
    
        def __set__(self, instance, value):
            if not isinstance(value, self.type_):
                value = self.factory(value)
            setattr(instance, self.key, value)
    
        def __delete__(self, instance):
            delattr(instance, self.key)
    
    class Book(object):
        isbn = TypeAdaptingProperty('isbn_', ISBNNumber)
    
    b = Book()
    b.isbn = 123 # Does the equivalent of b.isbn = ISBNNumber(123)
    

    However if you don’t fully control the message structure, such coupling isn’t a good idea. In such cases I like to use the interpreter pattern to adapt input messages to output types. I create a small framework that enables me to build declarative object structures to process the input data.

    The framework may look something like this:

    class Adaptor(object):
        """Any callable can be an adaptor. This base class just proxies calls
        to an appropriately named method."""
        def __call__(self, input):
            return self.adapt(input)
    
    class ObjectAdaptor(Adaptor):
        """Adaptor to create objects adapting the input value to the
        factory function/constructor arguments, and optionally setting
        fields after construction."""
        def __init__(self, factory, args=(), kwargs={}, fields={}):
            self.factory = factory
            self.arg_adaptors = args
            self.kwarg_adaptors = kwargs
            self.field_adaptors = fields
    
        def adapt(self, input):
            args = (adaptor(input) for adaptor in self.arg_adaptors)
            kwargs = dict((key, adaptor(input)) for key,adaptor in self.kwarg_adaptors.items())
            obj = self.factory(*args, **kwargs)
            for key, adaptor in self.field_adaptors.items():
                setattr(obj, key, adaptor(input))
            return obj
    
    def TypeWrapper(type_):
        """Converts the input to the specified type."""
        return ObjectAdaptor(type_, args=[lambda input:input])
    
    class ListAdaptor(Adaptor):
        """Converts a list of objects to a single type."""
        def __init__(self, item_adaptor):
            self.item_adaptor = item_adaptor
        def adapt(self, input):
            return map(self.item_adaptor, input)
    
    class Pick(Adaptor):
        """Picks a key from an input dictionary."""
        def __init__(self, key, inner_adaptor):
            self.key = key
            self.inner_adaptor = inner_adaptor
        def adapt(self, input):
            return self.inner_adaptor(input[self.key])
    

    The message adaptors look something like this:

    book_message_adaptor = ObjectAdaptor(Book, kwargs={
        'isbn': Pick('isbn_number', TypeWrapper(ISBNNumber)),
        'authors': Pick('authorlist', ListAdaptor(TypeWrapper(Author)))
    })
    

    Notice that the message structure names might not be the same as the object model.

    Message processing itself looks like this:

    message = {'isbn_number': 123, 'authorlist': ['foo', 'bar', 'baz']}
    book = book_message_adaptor(message)
    # Does the equivalent of:
    # Book(isbn=ISBNNumber(message['isbn_number']),
    #      authors=map(Author, message['author_list']))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I want to construct a data frame in an Rcpp function, but when I
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need to clean up various Word 'smart' characters in user input, including but
I know there's a lot of other questions out there that deal with this

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.