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.
P.S. 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:
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
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 *
.