K
K
Kirill Petrov2020-07-01 11:53:05
Python
Kirill Petrov, 2020-07-01 11:53:05

How to correctly determine the class of an object received from the network in python?

I guess in python, due to different entry points or namespaces, classes begin to differ. But let's move on to a simple example:
m2.py

import pickle
from m1 import Ab

if __name__ == '__main__':
    ab = Ab()

    with open('data.pickle', 'wb') as f:
        pickle.dump(ab, f)

m1.py
import pickle

class Ab:
    def __init__(self):
        pass

class DataReader:
    def __init__(self):
        pass

    def readPickle(self):
        with open('data.pickle', 'rb') as f:
            return pickle.load(f)

if __name__ == '__main__':
    ab = Ab()
    dataReader = DataReader()
    ab2 = dataReader.readPickle()
    print('ab', ab)
    print('ab2', ab2)

    if isinstance(ab, Ab):
        print('isinstance ab')

    if isinstance(ab2, Ab):
        print('isinstance ab2')

For an example of transferring from the network, I will give an example of transferring data through a file
. First, m2.py imports a class from a module, searilizes and saves (such as a network packet) into a file data.pickle
Next, m1.py is executed, reads data from a file and tries to determine whether they belong class. The output of the script is:
ab <__main__.Ab object at 0x03482E68>
ab2 <m1.Ab object at 0x0349C160>
isinstance ab


That is, it is clear here that ab2 has m1 written in front of the dot and, as I understand it, the second condition does not work because of this, if isinstance(ab2, Ab)and how in this case to check class membership?

And in the end I want to determine what type of data came from the network using OOP

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-07-02
@Recosh

Don't use pickle from external sources at all: this format allows arbitrary code to be executed on deserialization. Well, if you really want to, take out Ab in the general package.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question