jrjohansson / scientific-python-lectures

Lectures on scientific computing with python, as IPython notebooks.
3.51k stars 1.8k forks source link

hasattr() getattr() setattr() #23

Open westurner opened 10 years ago

westurner commented 10 years ago

http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-1-Introduction-to-Python-Programming.ipynb#Type-utility-functions

Something like:

import collections
from collections import OrderedDict
_Thing = collections.namedtuple('_Thing', ('attr1', 'attr2'))
class Thing(_Thing):
    pass

values = [
    True,
    0b01,
    0x42,
    1e42,
    42,
    42.0,
    "str",
    [1,2,3],
    (1,2,3,),  # tuples are immutable (but their references are not)
    {1,2,3},
    {'one':1,'two':2},
    OrderedDict([('one',1), ('two', 2)]),
    Thing(attr1=1, attr2=2),
    (x for x in range(4)),
    [x for x in range(2)],
]
print("# type, obj, iter(obj), list(iter(obj))")
for obj in values:
    output = (type(obj), obj, iter(obj), list(iter(obj))) if hasattr(obj, '__iter__') else (obj,)
    print(obj)

# ...

# * https://docs.python.org/3/whatsnew/2.7.html#python-3-1-features

And then something about tablib, dataset, pandas etc for reading/writing actual safe CSV.