When can you dynamically add a field to an object? - python

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?

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'

Related

AttributeError with extended class in Python

I'm trying to create a new method for a class from a different file (not the file where the class was defined). My code is:
from derivations import derivation
class Derivation(derivation.Derivation):
def autoderive(self, index):
...
deriv = derivation.Derivation()
But if I try to run this method from the terminal, it doesn't work:
>>> deriv.autoderive()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Derivation' object has no attribute 'autoderive'
I don't have problems with the "native" methods. And I'm working with a fork of this: https://github.com/alexwarstadt/minimalism
Thank you very much.
I do not know much about the derivation module, but you are not creating an instance of your Derivation class, where you have defined the autoderive method, by doing this:
deriv = derivation.Derivation()
To create an instance of your custom class Derivation, that derives from derivation.Derivation():
deriv = Derivation()

KeyError if I change constructor variable names

I'm going crazy trying to perform simple editing while creating a Python class constructor. I can create the simple class and constructor variable but once I try to change the names of the variable I get a KeyError.
The class is below:
class Collect:
def __init__(self, **kwargs):
self.foo = kwargs["foo"]
And the script where I instantiate the class and print out its attributes is below:
import mapper as m
payload = m.Collect(foo="Hello")
print(payload.foo)
Now this works just fine, but if I change "foo" to "bar" I get a KeyError Like below:
class Collect:
def __init__(self, **kwargs):
self.bar = kwargs["bar"]
and then running:
import mapper as m
payload = m.Collect(bar="Hello")
print(payload.bar)
will throw the following error:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> File
"/path/to/mapper.py",
line 8, in __init__
self.bar = kwargs["bar"] KeyError: 'foo'
And the print function will throw the error below:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> AttributeError: 'Collect' object has no attribute 'bar'
The weird thing is that if I hit save and then close VSCode and reopen, the new class with bar will work just fine. And, also even if I don't close VSCode the class will instantiate and the print statement will run just fine when I switch to Debug mode and run it. But when I try to highlight it and run a selection it throws that error.
How can I just test if the code works using the run selection operations and not relying on running in debug mode with breakpoints or having to close and reopen VSCode?
The solution was to reload my Python session. The VSCode reload extension makes this easy.

How to get a class object from class name

I want to get a class reference from class object in Python. Normally I use class name as a valid reference, but it does not always work.
Consider this code:
import inspect
import unittest
import pywin32_testutil
mro=inspect.getmro(pywin32_testutil.TestProgram)
mro[0]
> <class 'pywin32_testutil.TestProgram'>
mro[0].__module__ + '.' + mro[0].__name__
>'pywin32_testutil.TestProgram'
pywin32_testutil.TestProgram
> <class 'pywin32_testutil.TestProgram'>
From the object I'm able to determine class name and using class name I can get class object. However it does not always work. Continuing the example:
mro[1]
> <class 'unittest.main.TestProgram'>
mro[1].__module__ + '.' + mro[1].__name__
> 'unittest.main.TestProgram'
so far so good, however unittest.main.TestProgram reference is invalid:
unittest.main.TestProgram
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'TestProgram' has no attribute 'TestProgram'
How can I work around that?

Why do I get an AttributeError on getattr in my execute method?

The code below is used as part of a SimpleXMLRPCServer to receive commands from a Java client I've written. The Java client will just call this execute function and pass in a function name from the CameraAssembler class.
from nsCamera.CameraAssembler import CameraAssembler
class MyFunctions:
ca = None
def initialize(self):
# Create Camera object
self.ca = CameraAssembler(commname=COMM, boardname=BOARD, sensorname=SENSOR, verbose=True)
return True
def execute(self, code):
func = getattr(self.ca,code)
output = func()
return output
myfuncs = MyFunctions()
myfuncs.initialize()
output = myfuncs.execute('arm()')
print(output)
Output:
Traceback (most recent call last):
File "pyTestServer.py", line 31, in <module>
output = myfuncs.execute("arm()")
File "pyTestServer.py", line 21, in execute
func = getattr(MyFunctions.ca,code)
AttributeError: CameraAssembler instance has no attribute 'arm()'
Your parentheses are in the wrong place. The attribute is not called arm(), it's called arm; you need to call the result of getting that attribute.
output = myfuncs.execute('arm')()
(Note, this code isn't particularly idiomatic. In particular, I can't see why you're setting ca as a class attribute, rather than an instance one. Also, initialisation usually goes in an __init__ method, which is called automatically on instantiation.)

functools.partial as IronPython EventHandler

I'm currently trying out the IronPython interpreter. While doing the Tutorial i came across delegates and event handlers. The tutorial does something like this:
from System.IO import FileSystemWatcher
w = FileSystemWatcher()
def handle(*args):
print args
w.Changed += handle
So i tried to be smart and do this:
from System.IO import FileSystemWatcher
from __future__ import print_function
from functools import partial
w = FileSystemWatcher()
w.Changed += partial(print, "Changed: ")
Which failed with:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Object is not callable.
Where line 1 refers to the last line in the (interactive session)
So IronPython thinks a partial object is not callable although callable(partial(print, "Changed: ")) returns True
With this workaround the handler is accepted:
w.Changed += partial(print, "Changed: ").__call__
My question:
Why is a partial object not accepted as an event handler. Is this a bug?
This is probably not solution, one could expect, but there is an issue, opened for couple years now - https://github.com/IronLanguages/main/issues/808
Doesn't work in 2.6.2 and 2.7b1 on .NET Version: 4.0.30319.1 ipy26
testcase-26482.py
Object is not callable.
ipy27 testcase-26482.py
Object is not callable.py
testcase-26482.py
Object is not callable.

Categories

Resources