aaaantoine
aaaantoine

Reputation: 900

Print the same output as shown in the Python REPL

Consider the following Python shell dump:

>>> from datetime import datetime
>>> d = datetime(2014,1,1)
>>> d
datetime.datetime(2014, 1, 1, 0, 0)
>>> print(d)
2014-01-01 00:00:00

How can I create the string 'datetime.datetime(2014, 1, 1, 0, 0)' within a Python 3 program?

My objective is to generate code from a snapshot of data in order to provide a fixed set of data for unit testing. I tried searching "python print repl output" and similar terms, and didn't find the answer I was hoping for.

Upvotes: 0

Views: 569

Answers (1)

aaaantoine
aaaantoine

Reputation: 900

I had a look at the list of built-in functions and repr(object) caught my eye.

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

Sample code, extending from the question's terminal:

>>> repr(d)
'datetime.datetime(2014, 1, 1, 0, 0)'
>>> print(repr(d))
datetime.datetime(2014, 1, 1, 0, 0)

Upvotes: 1

Related Questions