danielgtaylor / danielgtaylor/python-betterproto

Dictionary representation improvement?

Offen
#252 0 Kommentare 5 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
enhancement
Vorherrschende Sprache
Python
Sterne
1.8k
Forks
234
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

Is there a better way to represent this dictionary into a `Struct()`? (Currently using 2.0.0b3)

```python
capability_dict = {"@context": "https://w3id.org/security/v2",
"target": "urn:trinsic:wallets:noop",
"proof": {
"created": datetime.datetime.now()
}
}
```
The following does work, but seems pretty kludgy:
```python
proof = Struct()
proof.fields["created"] = Value(string_value=str(datetime.datetime.now()))
capability = Struct()
capability.fields["@context"] = Value(string_value="https://w3id.org/security/v2")
capability.fields["target"] = Value(string_value="urn:trinsic:wallets:noop")
capability.fields["proof"] = Value(struct_value=proof)
```

* It seems to me that we could/should at least have a `Struct.from_dictionary(obj: dict)` method. I'd be happy to write this if it doesn't exist.
* `Struct.from_dict()` does NOT work for this, tested.

Example code of what I'm thinking:
```python
def value_to_proto_value(obj: Any) -> Value:
value = Value()
if isinstance(obj, str) or isinstance(obj, datetime.datetime):
value = Value(string_value=str(obj))
elif isinstance(obj, int) or isinstance(obj, float):
value = Value(number_value=float(obj))
elif isinstance(obj, bool):
value = Value(bool_value=obj)
elif isinstance(obj, dict):
value = Value(struct_value=dictionary_to_struct(obj))
elif isinstance(obj, list):
value = Value(list_value=list_to_proto_list(obj))

return value

def list_to_proto_list(obj: List) -> ListValue:
return ListValue(values=[value_to_proto_value(item) for item in obj])

def dictionary_to_struct(obj: Dict[str, Any]) -> Struct:
return Struct(fields=dict([(k, value_to_proto_value(v)) for k, v in obj.items()]))
```

Beitragsleitfaden

Beitragsleitfaden öffnen

Rechercherichtung

Start by locating the Struct, Value, and ListValue definitions and inspecting why Struct.from_dict() does not handle the shown nested dictionary. Confirm the intended conversion behavior for nested dictionaries, lists, strings, numbers, booleans, and datetime values. Done means an agreed ergonomic API and coverage for the example representation.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
developer-experience
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
30/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.