1

Working with namedtuple and I'm trying to put a query into it.

build = namedtuple('build', 'x y z')
build(x=DB.query(x).filter(x.id == 'query').first(),
      y=DB.query(y).filter(y.id == 'query').first(),
      z=DB.query(z).filter(z.id == 'query').first())

When I actually try to access x with print build.x.id I get:

AttributeError: 'property' object has no attribute 'id'

I think this has to do with having a query within the namedtuple, and I'm just doing it wrong or it isn't designed to do this. I've googled around and I don't see much on this.

Jer_TX
  • 465
  • 4
  • 20
  • Try: `print build.x['id']` – nivix zixer Aug 23 '15 at 23:41
  • Tried that too. get this error: `TypeError: 'property' object has no attribute '__getitem__'` – Jer_TX Aug 23 '15 at 23:42
  • I don't think this has anything to do with `namedtuple` (but it might); can you give us some context on what exactly `DB` is? It just seems like whatever you're putting into `build` isn't actually what you think it is. – hfaran Aug 23 '15 at 23:55
  • Probably should've noted but thought it was assumed since I put `pyramid` as a tag. I'm using `sqlalchemy`, so the resulting query of `x` would normally be something like `` in which I could then go, `print x.id` and I would get say, an integer. – Jer_TX Aug 23 '15 at 23:58
  • Is you sample code exactly what you use in your real program? Asking because I can run your code without any problems. – van Aug 24 '15 at 07:19
  • It's close enough. Try connecting it up to a real database, replace `x` with an actual table. I couldn't get it to work. – Jer_TX Aug 24 '15 at 13:00

1 Answers1

1

Found a workaround that doesn't used namedtuple, as I don't think that's appropriate for my usecase (ie, I don't think it supports nested dicts/objects without finangling)

Found this question, Convert Python dict to object? and decided to adjust my code to use that instead.

build = {'x': DB.query(x).filter(x.id == 'query').first()}
build = bunchify(build)

Which now allows me to do

>>> print build.x.id
27

seamlessly.

Simple is better than complex.

Community
  • 1
  • 1
Jer_TX
  • 465
  • 4
  • 20