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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:18:29+00:00 2026-05-28T06:18:29+00:00

I find myself trying to convert constructor parameters to their right types very often

  • 0

I find myself trying to convert constructor parameters to their right types very often in my Python programs. So far I’ve been using code similar to this, so I don’t have to repeat the exception arguments:

class ClassWithThreads(object):
    def __init__(self, num_threads):
        try:
            self.num_threads= int(num_threads)
            if self.num_threads <= 0:
                raise ValueError()
        except ValueError:
            raise ValueError("invalid thread count")

Is this a good practice? Should I just don’t bother catching any exceptions on conversion and let them propagate to the caller, with the possible disadvantage of having less meaningful and consistent error messages?

  • 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-28T06:18:30+00:00Added an answer on May 28, 2026 at 6:18 am

    When I have a question like this, I go hunting in the standard library for code that I can model my code after. multiprocessing/pool.py has a class somewhat close to yours:

    class Pool(object):
    
        def __init__(self, processes=None, initializer=None, initargs=(),
                     maxtasksperchild=None):
            ...
            if processes is None:
                try:
                    processes = cpu_count()
                except NotImplementedError:
                    processes = 1
            if processes < 1:
                raise ValueError("Number of processes must be at least 1")
    
            if initializer is not None and not hasattr(initializer, '__call__'):
                raise TypeError('initializer must be a callable')
    

    Notice that it does not say

    processes = int(processes)
    

    It just assumes you sent it an integer, not a float or a string, or whatever.
    It should be pretty obvious, but if you feel it is not, I think it suffices to just document it.

    It does raise ValueError if processes < 1, and it does check that initializer, when given, is callable.

    So, if we take multiprocessing.Pool as a model, your class should look like this:

    class ClassWithThreads(object):
        def __init__(self, num_threads):
            self.num_threads = num_threads
            if self.num_threads < 1:
                raise ValueError('Number of threads must be at least 1')
    

    Wouldn’t this approach possibly fail very unpredictably for some
    conditions?

    I think preemptive type checking generally goes against the grain of Python’s
    (dynamic-, duck-typing) design philosophy.

    Duck typing gives Python programmers opportunities for great expressive power,
    and rapid code development but (some might say) is dangerous because it makes no
    attempt to catch type errors.

    Some argue that logical errors are far more serious and frequent than type
    errors. You need unit tests to catch those more serious errors. So even if you
    do do preemptive type checking, it does not add much protection.

    This debate lies in the realm of opinions, not facts, so it is not a resolvable argument. On which side of the fence
    you sit may depend on your experience, your judgment on the likelihood of type
    errors. It may be biased by what languages you already know. It may depend on
    your problem domain.

    You just have to decide for yourself.


    PS. In a statically typed language, the type checks can be done at compile-time, thus not impeding the speed of the program. In Python, the type checks have to occur at run-time. This will slow the program down a bit, and maybe a lot if the checking occurs in a loop. As the program grows, so will the number of type checks. And unfortunately, many of those checks may be redundant. So if you really believe you need type checking, you probably should be using a statically-typed language.


    PPS. There are decorators for type checking for (Python 2) and (Python 3). This would separate the type checking code from the rest of the function, and allow you to more easily turn off type checking in the future if you so choose.

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

Sidebar

Related Questions

I find myself creating Converters often and would like to be able to: right-click
I often find myself trying to search cell arrays like I would want to
I've been trying to study up on PHP lately, and I find myself getting
I'm trying to teach myself python right now, and I'm using exercises from Learn
I find myself always trying to fit everything into the OOP methodology, when I'm
I'm struggling myself trying to find an easy way to change the DateTime format
I find myself adding debugging print statements quite often -- stuff like this: print(a_variable_name:
I find myself using python for a lot of file management scripts as the
I've been trying to design a widget for my rails app and unfortunately find
I often find myself using lambdas as some sort of local functions to make

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.