Should a Pythonic class be checked for 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 you check the validity of the parameters in other ways? For example:
Class Comment (object):
... def __init__ (self, content, creater, IPAddress):
... self.content = content
... self.creater = creater
... self.ipaddress = IPAddress
It seems that everyone generally writes this, without checking whether the IPAddress is a valid IP address.
Python's coding purpose seems to be to trust developers, so there is no design like private. So should our trust go to the point of "not checking the validity of the parameters"?

Reply content:

In fact, this question has already been discussed, "We are all adults" (after all, we ' re all consenting adults here.)

A simple translation:
Nothing was really private in python. No class or class instance can
Keep away from all "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 so you ' ve got
A good reason and you ' re not making trouble. "

After all, we ' re all consenting adults.

Nothing in Python is really private. Any class or object will not prevent you from prying into their insides, which makes Python's introspection exceptionally powerful. Python's attitude to you is trust, it said: "Hey, if you want to try to use black magic, then be assured to go, I believe you must have their own reasons, know what they are doing, and will not poke a basket, understand donuts"

After all, we are adults, and understand that they are responsible for their actions, they know what they are doing, so what you want to do I will not stop you.

I think this design philosophy is the fundamental difference between Python and Java, and the same is true for parameter checking, not checking your parameters, because you are trusted. But what about the question? Of course, the exception is thrown. If you throw an exception, you'll be responsible for your own (try except in the right place, and assume you know what to do when you catch an exception).

Again, this idea runs through many places in Python, such as to let a Generator end, can throw a stopiteration exception, exception is not a scourge, but a normal phenomenon, the correct throw and capture of the exception to ensure that the world normal operation, in the Python is as important as the control flow. Why is it? is also a kind of trust thought, believed that the anomaly can be handled correctly, also should be handled correctly, and already in the language itself is handled correctly everywhere.

The class that the master writes, if you pass a problematic argument, the program usually throws an exception where it should go wrong. And the author of this class--you, as an adult, should be able to handle this anomaly correctly, and that is trust in you. You should know how to handle this exception, including knowing that you should do a certain parameter check when necessary (this does not conflict, it is still trust.) So you see, you want to do a parameter check and Python won't stop you.

When I was little, I said I wanted to ride my bike to another city to play and was stopped by my mother (parameter check).
If I were to go now, my mother said, "You are an adult, you should have your reasons, take care of yourself, but you are responsible for all the problems of your travels" (trust, unrestricted, assuming that the user is responsible for the problem).

Full text, see: [Tutor] What is "pythonic"? Inspection of input parameters is part of defensive programming

When you do not trust input, such as the user-provided data, or another server provides, it should be checked

However, it is not necessary to check the class initialization, if this is the Model class, you can also check before writing to the database

If this input is provided by a trusted module, or after a round of checks, there is no need to repeat
The purpose of Python is to trust developers to abide by development conventions, but not to say that trusted developers have no bugs, and that defensive programming does not conflict with any data in the document. The official Python does not support the unnecessary checking of types. Since even types are not checked, why check the validity of the values? The C language is also not always going to check that what the user is sending is right-it's the responsibility of the caller, and the repository's responsibility is to get the document up and not to guess where the data is coming from.

In Python, illegal data is passed in and always causes an exception (otherwise why do you say it's not legal?). )。 If you want to store that IP address in the database, or give it to the C function, it must be checked, and if it is passed to Socket.connect, why check it? Are you able to do the right checks? (Most of the website registration when the Email check too strict, such as do not allow + number; As for the IP address, how many people consider the IPV6? Do you all know that the value of the seconds range is 0-61? )

The personal understanding is that this is a language-neutral issue, not just python.

Separating a business's processing and checking incoming parameters is a good choice, but the separation is a class level, or the method level may need to be determined based on a specific business tradeoff. may need to implement the function is relatively simple, the parameters are relatively simple, method-level can be, if the subsequent requirements change, business logic complex, and then refactor the code is not too late.

A class is a good thing, based on a single principle of responsibility. Personal comparison preference the business is processed into a separate class, the parameters are checked for another class, and the two classes are placed in a file.

Dufu classmate's doubts are: should check the parameter in addition to the type of validity.
From the aspects of security, data integrity and so on, this type of check is necessary, such as the previous Evian classmate mentioned database operations. These checks should be specific to the business, and should not be checked before the last write (before writing is also checked, do not trust the input). The simple answer is that Python code should not be designed to require type checking. If you feel the need, it means that there is a problem with the design.
The answer to this stackoverflow is very good, it is recommended to read:
/ http stackoverflow.com/quest Ions/734368/type-checking-of-arguments-python In fact, you can build a class that enforces type checking through mechanisms such as metaclass. Input may not be standardized to check, but not necessarily in the __init__, you can adjust the other functions, such as
self.ipaddress = Self.validateip (ipaddress)

In fact, there is no need to care too much about Python specifications, a lot of things are not standardized, depending on the matter.


Also check the IP address recommended Google open source Python library / http Code.google.com/p/ipadd r-py/
Class does not check, which is in the input when the gatekeeper can be. Duck typing does not need to check the code type logic is: When the type is not appropriate when the natural error. But this is not contradictory to defensive programming. You should still judge the input validity at the module boundary, or wait until the end of the long call chain (if it is stored by the incoming class constructor, the call chain is long broken), how do you debug when you find it inappropriate? To yourself and the other people in the project. The "tacit understanding" of this place is that non-business logic code such as Corelib, utils to check the parameters, the business logic part of the user input check ... Others are not mandatory.
  • Related Article

    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.