简体   繁体   中英

Jsonpickle in subclass changes data type

In one of my projects I have a strange problem with jsonpickle , as long as I run it from the same file it works fine, but if it is run from a other class it changes the target object to dict. Below is simple problem reconstruction. My original classes are little complicated, but problem is the same.

PS Problem "disapears" when in gui.py I change import data to from data import * (with other code refactoring) but I'm not sure why...

Simple example:

  1. data.py - alone works fine
import jsonpickle
from dataclasses import dataclass, field
from typing import List

@dataclass
class Car:
    name: str
    model: str

class CarsList(List):
    # some other non important functions

    def length(self):
        return len(self)

class Company:

    def __init__(self):
        self.companyCars = CarsList()
        self.loadData()
        print(self.companyCars.length())

    def loadData(self):
        with open('cars.json', "r") as infile:
            json_str = infile.read()
        self.companyCars = jsonpickle.decode(json_str)

if __name__ == '__main__':
    myCompany = Company()  # works fine
  1. gui.py (not working)
import data
class Gui:
    def __init__(self):
        self.myCompany = data.Company()

if __name__ == '__main__':
    myGui = Gui()  # Not working !

Second file returns error:

Traceback (most recent call last):
  File "/home/bart/costam/gui.py", line 15, in <module>
    myGui = Gui()  # Not working !
  File "/home/bart/costam/gui.py", line 11, in __init__
    self.myCompany = data.Company()
  File "/home/bart/costam/data.py", line 40, in __init__
    print(self.companyCars.length())
AttributeError: 'dict' object has no attribute 'length'

The class is not available globally, so jsonpickle is not able to decode it.

In the docs : The object must be accessible globally via a module and must inherit from object (AKA new-style classes).

This is also why the problem 'disappears' when you do from data import * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM