-1

I am new to python & facing issue while accessing second element of iterateable returned by function from lib pyyaml, yaml.load_all, below is code:

import os
import yaml
file = "abc.yaml"
stream = open(file)
docs = yaml.load_all(stream)
print docs[1]

output I am getting is

TypeError: 'NoneType' object has no attribute '__getitem__'

yaml is python lib for handling yaml format, yaml.load_all is explained here

Shashank
  • 416
  • 5
  • 16
  • 2
    `docs` in this case is actually `None`, not an iterable. Can you please provide a full code example? What is `yaml` in this case? Where did it come from? – Ffisegydd Nov 21 '14 at 09:41
  • As @Ffisegydd said, it's `None` in this case. If it was iterable, you could use `next` function to get next element from iterable. – ferhatelmas Nov 21 '14 at 09:43
  • but then i can do a for on it eg: `for doc in docs: print doc` – Shashank Nov 21 '14 at 09:46
  • Again, can you please provide a fully working example? – Ffisegydd Nov 21 '14 at 09:49
  • this is completed code I have written so far – Shashank Nov 21 '14 at 09:51
  • 1
    @Shanky : you _can not_ "do a for" (=> iterate) on `None` - it very obviously raises a `TypeError` with 'NoneType' object is not iterable'. And your example is not "fully working" without the exact content of "abc.yaml". – bruno desthuilliers Nov 21 '14 at 09:53

2 Answers2

0

If you only need that one document, then this should do:

docs = yaml.load_all(...)
next(docs)  # skip docs[0]
mydoc = next(docs)
Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120
0

The error message you mention (TypeError: 'NoneType' object has no attribute '__getitem__') does not come from docs being a generator but from docs being None.

But anyway, to answer your question: you cannot "access element at an index in a generator", because generator are not subscriptable - the whole point of generators is to generate values on the fly. If you really need a subscriptable sequence, the simplest way is to build a list from your generator, ie:

docs = list(yaml.load_all(stream))

Now beware that you'd rather not do this unless you know for sure that 1. your generator is not infinite (generators can be infinite and some are) and 2. the list will fit in memory.

NB : I use the word "generator" here but it applies to iterators in general.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118