views:

139

answers:

3

In C++, you can do this to easily read data into a class:

istream& operator >> (istream& instream, SomeClass& someclass) {
    ...
}

In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?

+6  A: 

You are essentially looking for deserialization. Python has a myriad of options for this depending on the library used. The default is python pickling. There are lots of other options you can have a look here.

whatnick
+1  A: 

Rather than use raw_input, you can read from sys.stdin (a file-like object):

import sys
input_line = sys.stdin.readline()
# do something with input_line
dcrosta
+3  A: 

No, there's no widespread Pythonic convention for "read the next instance of class X from this open input text file". I believe this applies to most languages, including e.g. Java; C++ is kind of the outlier there (and many C++ shops forbid the operator>> use in their local style guides). Serialization (to/from JSON or XML if you need allegedly-human readable text files), suggested by another answer, is one possible approach, but not too hot (no standardized way to serialize completely general class instances to either XML or JSON).

Alex Martelli