Python: How to check that...?
I'd like some advice on how to check for the correctness of the parameters I receive.
The checking is going to be done in C++, so if there's a good solution using Boost.Python (preferably) or the C API, please tell me about that. Otherwise, tell me what attributes the object should have to ensure tha开发者_如何转开发t it meets the criteria.
So...
- How do you check that an object is a function?
- How do you check that an object is a bound method?
- How do you check that an object is a class object?
- How do you check that a class object is a child of another class?
When in doubt just work out how you would get the required effect by calling the usual Python builtins and translate it to C/C++. I'll just answer for Python, for C you would look up the global such as 'callable' and then call it like any other Python function.
Why would you care about it being a function rather than any other sort of callable? If you want you can find out if it is callable by using the builtin
callable(f)
but of course that won't tell you which arguments you need to pass when calling it. The best thing here is usually just to call it and see what happens.isinstance(f, types.MethodType)
but that won't help if it's a method of a builtin. Since there's no difference in how you call a function or a bound method you probably just want to check if it is callable as above.isinstance(someclass, type)
Note that this will include builtin types.issubclass(someclass, baseclass)
I have two unconventional recommendations for you:
1) Don't check. The Python culture is to simply use objects as you need to, and if it doesn't work, then an exception will occur. Checking ahead of time adds overhead, and potentially limits how people can use your code because you're checking more strictly than you need to.
2) Don't check in C++. When combining Python and C (or C++), I recommend only doing things in C++ that need to be done there. Everything else should be done in Python. So check your parameters in a Python wrapper function, and then call an unchecked C++ entry point.
精彩评论