base64 encoding vs pickling on python objects

Viewed 9471

I have not used pickling and encoding much with Python. But, just as I came to know about them, I was thinking that I could perform the same operation of converting a python object to a string using 2 different ways.

#1: Using pickle module

>>> encoded = pickle.dumps(range(10))
>>> pickle.loads(encoded)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#2: Using Base64 Encoding

# First I'l define encode and decode functions for convenience.

def encode(obj):
    string = json.dumps(obj)
    return base64.b64encode(string)

def decode(string):
    decoded_string = base64.b64decode(string)
    return json.loads(decoded_string)

# Encode and Decode.
>>> encoded = encode(range(10))
>>> decode(encoded)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

base64

What are their typical use cases and which method is more efficient in its performance?

UPDATE:

I understand now that my question does not make much sense. Comparing json and pickle would be a better question. Base64 encoding can be performed on both json or pickled strings and is used for creating an ASCII only string encoding; example: for passing data as GET parameter in urls.

2 Answers

Pickle got many advantages and capabilities comparing to base64.

for example:

class A:
    """class def here"""
    pass

a = A()

apick = pickle.dumps(a)
print(apick)

# this scenario even works when apick is send to a different python instance where A is **not** defined

b = pickle.loads(apick)

but in my opinion sending a byte string by using base64 is faster if we are aware of what we are really doing.

Related