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 7728845
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T05:49:15+00:00 2026-06-01T05:49:15+00:00

I have many different small classes which have a few fields each, e.g. this:

  • 0

I have many different small classes which have a few fields each, e.g. this:

class Article:
    def __init__(self, name, available):
        self.name = name
        self.available = available

What’s the easiest and/or most idiomatic way to make the name field read only, so that

a = Article("Pineapple", True)
a.name = "Banana"  # <-- should not be possible

is not possible anymore?

Here’s what I considered so far:

  1. Use a getter (ugh!).

    class Article:
        def __init__(self, name, available):
            self._name = name
            self.available = available
    
        def name(self):
            return self._name
    

    Ugly, non-pythonic – and a lot of boilerplate code to write (especially if I have multiple fields to make read-only). However, it does the job and it’s easy to see why that is.

  2. Use __setattr__:

    class Article:
        def __init__(self, name, available):
            self.name = name
            self.available = available
    
        def __setattr__(self, name, value):
            if name == "name":
                raise Exception("%s property is read-only" % name)
            self.__dict__[name] = value
    

    Looks pretty on the caller side, seems to be the idiomatic way to do the job – but unfortunately I have many classes with only a few fields to make read only each. So I’d need to add a __setattr__ implementation to all of them. Or use some sort of mixin maybe? In any case, I’d need to make up my mind how to behave in case a client attempts to assign a value to a read-only field. Yield some exception, I guess – but which?

  3. Use a utility function to define properties (and optionally getters) automatically. This is basically the same idea as (1) except that I don’t write the getters explicitely but rather do something like

    class Article:
        def __init__(self, name, available):
            # This function would somehow give a '_name' field to self
            # and a 'name()' getter to the 'Article' class object (if
            # necessary); the getter simply returns self._name
            defineField(self, "name")
            self.available = available
    

    The downside of this is that I don’t even know if this is possible (or how to implement it) since I’m not familiar with runtime code generation in Python. 🙂

So far, (2) appears to be most promising to me except for the fact that I’ll need __setattr__ definitions to all my classes. I wish there was a way to ‘annotate’ fields so that this happens automatically. Does anybody have a better idea?

For what it’s worth, I’mu sing Python 2.6.

UPDATE:
Thanks for all the interesting responses! By now, I have this:

def ro_property(o, name, value):
    setattr(o.__class__, name, property(lambda o: o.__dict__["_" + name]))
    setattr(o, "_" + name, value)

class Article(object):
    def __init__(self, name, available):
        ro_property(self, "name", name)
        self.available = available

This seems to work quite nicely. The only changes needed to the original class are

  • I need to inherit object (which is not such a stupid thing anyway, I guess)
  • I need to change self._name = name to ro_property(self, "name", name).

This looks quite neat to me – can anybody see a downside with it?

  • 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-06-01T05:49:17+00:00Added an answer on June 1, 2026 at 5:49 am

    I would use property as a decorator to manage your getter for name (see the example for the class Parrot in the documentation). Use, for example, something like:

    class Article(object):
        def __init__(self, name, available):
            self._name = name
            self.available = available
    
        @property
        def name(self):
            return self._name
    

    If you do not define the setter for the name property (using the decorator x.setter around a function) this throws an AttributeError when you try and reset name.

    Note: You have to use Python’s new-style classes (i.e. in Python 2.6 you have to inherit from object) for properties to work correctly. This is not the case according to @SvenMarnach.

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

Sidebar

Related Questions

I have a base class object array into which I have typecasted many different
I have seen this problem arise in many different circumstances and would like to
I have an application that has many different types of objects that each persist
I have a shared memory pool from which many different threads may request an
I have many different branches/checkouts of the same project code on my development machine.
I have a database that many different client applications (a smattering of web services,
I have many emails coming in from different sources. they all have attachments, many
I have an application with many different parts, it runs on OSGi, so there's
I have many tables with identical schemas but different names. Can I create a
I have a servlet that is used for many different actions, used in the

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.