Question

I'm learning curses in python, and wanted to add an attribute to the curses window object.

my minimal program is:

import curses
try:
  stdscr = curses.initscr()
  stdscr.cur_line = 0
finally: 
  #clean-up so your terminal isn't wrecked by above error
  curses.nocbreak()
  stdscr.keypad(False)
  curses.echo()
  curses.endwin()

The error is:

$ python3 tmp
Traceback (most recent call last):
  File "tmp", line 4, in <module>
    stdscr.cur_line = 0
AttributeError: '_curses.curses window' object has no attribute 'cur_line'

However, this works:

class Temp:
    def __init__(self):
        pass
t = Temp()
t.cur_line = 0 #does not fail

My questions is: When does dynamically adding a field to an instance fail? How is python discerning between an instance of my user defined class, and an instance of the class from the curses library?

Was it helpful?

Solution

Most often, this happens because you're trying to add attributes to libraries written in C, and not pure python objects.

>>> import pickle, cPickle
>>> pickle.dump.a=1
>>> cPickle.dump.a=1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'a'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top