Skip to content

Instantly share code, notes, and snippets.

@fuji44
Last active June 13, 2021 14:00
Show Gist options
  • Save fuji44/fc2d9079be8754b03f2b6c624f625edc to your computer and use it in GitHub Desktop.
Save fuji44/fc2d9079be8754b03f2b6c624f625edc to your computer and use it in GitHub Desktop.
Python code to find the fields of an object
from dataclasses import dataclass, field
def get_member(cls) -> list[str]:
return [x for x in dir(cls) if not x.startswith("_")]
@dataclass
class Product:
# If you do not specify a field, that field will not be detected.
id: str
name: str = field(default=None)
type: str = field(default="A01")
description: str = field(default="")
p1 = Product(
id="id01",
name="Product 1",
type="B01",
description="xxx"
)
get_member(Product)
# ['description', 'name', 'type']
get_member(p1)
# ['description', 'id', 'name', 'type']
from dataclasses import dataclass, field
import inspect
def get_member(cls) -> list[str]:
return [x for x in inspect.getmembers(cls) if not x[0].startswith("_")]
@dataclass
class Product:
# If you do not specify a field, that field will not be detected.
id: str
name: str = field(default=None)
type: str = field(default="A01")
description: str = field(default="")
p1 = Product(
id="id01",
name="Product 1",
type="B01",
description="xxx"
)
get_member(Product)
# [('description', ''), ('name', None), ('type', 'A01')]
get_member(p1)
# [('description', 'xxx'), ('id', 'id01'), ('name', 'Product 1'), ('type', 'B01')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment