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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T22:47:47+00:00 2026-05-29T22:47:47+00:00

How do I restrict a class member variable to be a specific type in

  • 0

How do I restrict a class member variable to be a specific type in Python?


Longer version:

I have a class that has several member variables which are set externally to the class. Due to the way they’re used, they must be of specific types, either int or list.

If this was C++, I would simply make them private and do type-checking in the ‘set’ function. Given that that isn’t possible, is there any way to restrict the type of the variables so that an error/exception occurs at runtime if they’re assigned a value of incorrect type? Or do I need to check their type within every function that uses them?

  • 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-29T22:47:49+00:00Added an answer on May 29, 2026 at 10:47 pm

    You can use a property like the other answers put it –
    so, if you want to constrain a single attribute, say "bar",
    and constrain it to an integer, you could write code like this:

    class Foo(object):
        def _get_bar(self):
            return self.__bar
        def _set_bar(self, value):
            if not isinstance(value, int):
                raise TypeError("bar must be set to an integer")
            self.__bar = value
        bar = property(_get_bar, _set_bar)
    

    And this works:

    >>> f = Foo()
    >>> f.bar = 3
    >>> f.bar
    3
    >>> f.bar = "three"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in _set_bar
    TypeError: bar must be set to an integer
    >>> 
    

    (There is also a new way of writing properties, using the "property" built-in as a decorator to the getter method – but I prefer the old way, like I put it above).

    Of course, if you have lots of attributes on your classes, and want to protect all of them in this way, it starts to get verbose. Nothing to worry about – Python’s introspection abilities allow one to create a class decorator that could automate this with a minimum of lines.

    def getter_setter_gen(name, type_):
        def getter(self):
            return getattr(self, "__" + name)
        def setter(self, value):
            if not isinstance(value, type_):
                raise TypeError(f"{name} attribute must be set to an instance of {type_}")
            setattr(self, "__" + name, value)
        return property(getter, setter)
    
    def auto_attr_check(cls):
        new_dct = {}
        for key, value in cls.__dict__.items():
            if isinstance(value, type):
                value = getter_setter_gen(key, value)
            new_dct[key] = value
        # Creates a new class, using the modified dictionary as the class dict:
        return type(cls)(cls.__name__, cls.__bases__, new_dct)
    

    And you just use auto_attr_checkas a class decorator, and declar the
    attributes you want in the class body to be equal to the types the attributes need to constrain too:

    ...     
    ... @auto_attr_check
    ... class Foo(object):
    ...     bar = int
    ...     baz = str
    ...     bam = float
    ... 
    >>> f = Foo()
    >>> f.bar = 5; f.baz = "hello"; f.bam = 5.0
    >>> f.bar = "hello"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in setter
    TypeError: bar attribute must be set to an instance of <type 'int'>
    >>> f.baz = 5
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in setter
    TypeError: baz attribute must be set to an instance of <type 'str'>
    >>> f.bam = 3 + 2j
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in setter
    TypeError: bam attribute must be set to an instance of <type 'float'>
    >>> 
    
        
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can we restrict Type property of a class to be a specific type? Eg:
I want to create a generic class that takes a type parameter and restrict
I have a class User, which has many Events and belongs to many Groups.
I have a base class with several derived classes that extend it. I want
I have a service class implemented in Java 6 / Spring 3 that needs
We can restrict type of method parameters; for example, we should say that function
I have two closely related classes which I'll call Widget and Sprocket. Sprocket has
i'm with a trouble; For initial imagine that we have an entity Member, and
This member has a SecurityCriticalAttribute attribute, which restricts it to internal use by the
I have a file with several related functions which need to share a piece

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.