Beginners question
Marco Nawijn
nawijn at gmail.com
Thu Aug 30 08:23:43 EDT 2012
On Thursday, August 30, 2012 1:54:08 PM UTC+2, (unknown) wrote:
> Hello
>
>
>
> I'm slowly teaching myself python so apologies if this is a dumb question.
>
> but something has confused me with the os.stat() function:
>
>
>
> >>> s = os.stat(".")
>
> >>> print s
>
> posix.stat_result(st_mode=16877, st_ino=2278764L, st_dev=2053L, st_nlink=2, st_u
>
> id=1000, st_gid=100, st_size=4096L, st_atime=1346327745, st_mtime=1346327754, st
>
> _ctime=1346327754)
>
>
>
> What sort of object is posix.stat_result? Its not a dictionary or list or a
>
> class object as far as I can tell. Thanks for any help.
>
>
>
> B2003
Hi,
So let's try to figure this out. First of all, we can ask Python what object it is.
>>> s = os.stat('.')
>>> type(s)
posix.stat_result
So it seems to be a custom type. However types can inherit from builtins like
list, tuple and dict, so maybe it still is a dict or a tuple. Let's ask Python again:
>>> isinstance(s, dict)
False
>>> isinstance(s, (tuple, list))
False
Ok. So it is neither a list (tuple) nor a dict. So without reverting to the source code, it is probably save to say that the result is a custom class where the attributes can be accessed by the dot '.' notation. This is confirmed when you do:
>>> dir(s)
......
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'n_fields',
'n_sequence_fields',
'n_unnamed_fields',
'st_atime',
'st_blksize',
'st_blocks',
'st_ctime',
'st_dev',
'st_gid',
'st_ino',
'st_mode',
'st_mtime',
'st_nlink',
'st_rdev',
'st_size',
'st_uid']
For example:
>>> print s.st_size
4096
In case of Linux I think that the result of os.stat(..) is a wrapping of a C struct (a class with only attributes and no methods).
A small additional remark. Besides being a real dict or list (by means of inheritance), custom class can also implement the interface (__getitem__ etc.). If you want to know if an object implements this interface you could use the types defined in the 'abc' and 'collections' standard modules. So instead of checking if a type is a dict like this:
>>> isinstance(s, dict)
you could also check if it implements the dict interface:
>>> isinstance(s, collections.MutableMapping) # or similar
Regards,
Marco
More information about the Python-list
mailing list