如何实现无需重复传入类本身即可获取Pydantic类的所有字段名?
Absolutely, there are several straightforward ways to clean up your implementation so you don't have to pass the class itself to get_all_fields(), or even make the field list directly accessible as a class property. Let's walk through the best options:
Option 1: Use a @classmethod for Dynamic Field Retrieval
The simplest fix is to convert your get_all_fields method into a class method. This way, the method automatically receives the class itself as its first parameter (cls), eliminating the need to pass it manually.
Here's the updated code:
from pydantic import BaseModel class AdaptedModel(BaseModel): @classmethod def get_all_fields(cls, alias=False): return list(cls.schema(by_alias=alias).get("properties").keys()) class TestClass(AdaptedModel): test: str
Now you can call it cleanly like this:
# No need to pass TestClass twice! fields = TestClass.get_all_fields() # With alias=True if you need to use field aliases fields_with_aliases = TestClass.get_all_fields(alias=True)
This keeps the flexibility of toggling the alias parameter while making the call syntax intuitive and readable.
Option 2: Auto-Generate a Class Property for Static Field Access
If you don't need to dynamically switch the alias parameter and just want direct, one-shot access to the field list, you can use __init_subclass__ to compute the fields once when the subclass is defined. This is more efficient since it runs only once, not every time you request the fields.
Updated code:
from pydantic import BaseModel class AdaptedModel(BaseModel): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # Store regular field names as a class attribute cls.all_fields = list(cls.schema().get("properties").keys()) # Optional: Add alias-based fields if you need them cls.all_fields_with_aliases = list(cls.schema(by_alias=True).get("properties").keys()) class TestClass(AdaptedModel): test: str
Now you can access the fields directly without any method calls:
print(TestClass.all_fields) # Output: ['test'] # If you added the alias version: # print(TestClass.all_fields_with_aliases)
Which Option Should You Choose?
- Use the
@classmethodapproach if you need the flexibility to sometimes retrieve fields using their aliases (via thealiasparameter). - Use the class property approach if you just need a static list of field names and want the most concise, readable access possible.
Both solutions eliminate the clunky dm.TestClass.get_all_fields(dm.TestClass) syntax and make your code much cleaner.
内容的提问来源于stack exchange,提问作者5th

