You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中验证给定输入是否为对象?求非Django方案

How to Write a Function to Validate if Input is an Object

Got it, let's cut through the noise—those Django form results are totally not what you need here, since you're looking for a generic way to check if an input qualifies as an "object" (the exact definition depends on your programming language, so I'll cover the most common scenarios).

First, let's clarify: when you say "object," do you mean a plain key-value pair object (like JavaScript's plain objects or Python's dictionaries), or any instance of a custom class? Let's break down both cases for the two most common languages:

For JavaScript

JavaScript has a weird quirk where typeof null returns "object", plus arrays are technically objects too—so you'll want to exclude those if you're targeting plain objects. Here's a robust function:

function isPlainObject(input) {
  // First rule out null and non-object types
  if (input === null || typeof input !== 'object') {
    return false;
  }
  // Use Object.prototype.toString to avoid mistaking arrays/other built-ins for plain objects
  return Object.prototype.toString.call(input) === '[object Object]';
}
  • This checks that the input is an object, isn't null, and isn't an array/Date/Map/etc. (those would return different strings from toString.call()).
  • If you don't care about excluding arrays and just want any kind of object (including arrays), simplify it to:
    function isObject(input) {
      return typeof input === 'object' && input !== null;
    }
    

For Python

Python treats almost everything as an object, so you need to be specific:

  • If you're checking for a dictionary (the equivalent of JS's plain object):
    def is_dict_object(input):
        return isinstance(input, dict)
    
  • If you want to check for custom class instances (excluding built-in types like lists, strings, numbers):
    def is_custom_object(input):
        # List of built-in types to exclude
        excluded_types = (int, str, float, bool, list, dict, tuple, set, frozenset)
        if isinstance(input, excluded_types):
            return False
        # All other things are instances of custom classes or complex built-ins
        return isinstance(input, object)
    

Key Questions to Refine Your Function

Before finalizing, ask yourself:

  • Do I need to exclude built-in objects (like Date in JS or datetime in Python)?
  • Should arrays/lists count as "objects" for my use case?
  • What edge cases do I need to handle? (null/None, primitives like strings/numbers, etc.)

Start with a clear definition of what you consider an "object," then tweak the function to match that definition—it'll make the validation way more reliable.

内容的提问来源于stack exchange,提问作者user12598931

火山引擎 最新活动