Should a Pythonic class check the parameter validity in _ init?

Source: Internet
Author: User
I know that according to the duck type principle, the parameter type should not be checked. But should we check whether the parameter is valid in other aspects? For example: classComment (object ):... def _ init _ (self, content, creater, ipaddress ):...... self. contentcontent ...... self. creatercreater ...... self. I know that according to the duck type principle, the parameter type should not be checked. But should we check whether the parameter is valid in other aspects? For example:
Class Comment (object ):
... Def _ init _ (self, content, creater, ipaddress ):
...... Self. content = content
... Self. creater = creater
... Self. ipaddress = ipaddress
It seems that most people do this without checking whether ipaddress is a valid IP address.
Python seems to be designed to trust developers, so there is no private design. So should our trust be "no check for parameter validity? Reply: in fact, this question has already been discussed. "we are all adults" (After all, we're all consenting adults here .)

Simple translation section:
Nothing is really private in python. No class or class instance can
Keep you away from all what's inside (this makes introspection
Possible and powerful). Python trusts you. It says "hey, if you want
To go poking around in dark places, I'm gonna trust that you're 've got
A good reason and you're not making trouble ."

After all, we're all consenting adults here.

Nothing in Python is actually private. no class or object will prevent you from spying on them, which makes Python's introspection very powerful. python's attitude towards you is trustworthy. it says, "hey, if you want to try black magic, you can rest assured that you have your own reasons, I know what I am doing, and I don't know what I am doing. I know what I am doing"

After all, everyone is an adult and knows what they are doing for their own actions. so what do you want? I won't block you.

I think this design philosophy is the fundamental difference between Python and Java. The same is true for parameter checks. if you do not check your parameters, trust you. But what if I ask? Of course, an exception is thrown. If an exception is thrown, you need to take responsibility for it (try again T in the appropriate place, and assume that you know how to handle the exception after capturing it ).

This idea runs through many places in Python. for example, if you want to end a Generator, you can throw a StopIteration exception, which is not a norm, but a normal phenomenon, the correct throwing and capturing of exceptions ensures the normal operation of the world. the importance in Python is comparable to the control flow. Why? It is also a concept of trust. we believe that exceptions can be handled correctly and correctly, and they have been correctly handled everywhere in the language itself.

The class written by the subject. if you pass a problematic parameter, the program usually throws an exception where the problem occurs. The author of this category-you, as an adult, should be able to correctly handle this exception, which is a trust in you. You should know how to handle this exception, including knowing that you should perform certain parameter checks when necessary (this is not a conflict, and it is still trust. So you can see that Python does not block you if you want to check the parameters ).

When I was a child, I didn't know anything. I said I wanted to ride a bike to another city and was stopped by my mom (parameter check ).
If I want to go now, my mom says, "you are an adult. you should have your own reasons and take care of yourself, however, you are responsible for all your travel problems. "(trust is not limited. assume that the user is responsible for the problem ).

For the full text, see [Tutor] What is "pythonic "? Input parameter check is part of defensive programming

When you do not trust the input, such as the data provided by the user or provided by another server, you should check

But it is not necessary to check during class initialization. if this is a Model class, you can also check before writing data to the database.

If this input is provided by a trusted module, or has already passed a round of checks, there is no need to repeat it.
The purpose of Python is to trust developers to abide by the development conventions, but it does not mean that the programs that trust developers have no bugs, and there is no conflict with defensive programming. in this document, it is enough to indicate the desired data. Python does not support unnecessary checks. Since the connection type is not checked, why check the value validity? C language also does not always check whether the user has passed in correctly-this is the caller's responsibility. the library's responsibility lies in the preparation of the document, so don't let people guess where to pass in the data.

In Python, an exception always occurs after illegal data is passed in (otherwise, why do you say it is not legal ?). If you want to store the IP address in the database immediately or hand it over to the C function, you must check it. if it is passed to socket. connect, why check it? Can you check correctly? (For most websites, the Email check is too strict during registration, for example, the + number is not allowed. as for IP addresses, how many people have taken IPv6 into account? Do you all know that the value range of seconds is 0-61 ?)

My personal understanding is that this is a language-independent issue, not just python.

Separating the input parameters of Service Processing and inspection is a good choice. However, whether this separation is a class level or a method level may need to be determined based on the specific business trade-offs. The functions to be implemented may be relatively simple, the parameters are relatively simple, and the method level is enough. if the requirements change in the future, the business logic is complicated, and it is not too late to refactor the code.

Based on the single responsibility principle, one class does one thing well. I personally prefer to process the business into an independent class, check the parameter as another class, and put the two classes in one file.

Jiang Ge's question is: should we check whether the parameter is valid except for the type.
In terms of security and data integrity, this type of check is necessary, such as the database operations mentioned by cloud students. These checks should be related to specific services and should not be checked before the last write (check is also required before writing, do not trust the input ). The simple answer is: Python code should not be designed to require type checks. If you need it, it means there is a problem with the design.
The answer to this stackoverflow is good. Read the following:
Http://stackoverflow.com/questions/734368/type-checking-of-arguments-python In fact, you can use metaclass and other mechanisms to build a class that enforces type checks. Check the input may be nonstandard, but it may not be in _ init _. you can call another function, such
Self. ipaddress = self. validateip (ipaddress)

In fact, you don't need to care too much about the python specifications. many things have no standards, and they are regarded as things.


Also check IP address recommendation Google Open Source python library http://code.google.com/p/ipaddr-py/
If the class is not checked, you can check the input. The logic that does not need to check the code type for Duck typing is: when the type is not suitable, errors will naturally occur. However, this is not in conflict with defensive programming. You should still judge the input validity at the module boundary. Otherwise, wait until the end of the long call chain (if it is stored as an input class constructor, the call chain has been broken for a long time) how do you debug when it is not suitable? The "tacit understanding" for yourself and other people in the project team is that non-business logic code, such as corelib, utils, checks the parameters, and some users in the business logic enter the check... others are not mandatory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.