Syntax Error When Importing List of Class Objects - python

I have a program where I want to store a list of class objects in another file. To do this i add objects to a list and then save that list to another file using this code. However, when my program tries to import the list back, it fails.
Here is my code
import sys
from test_two import *
print(test_list)
class Test:
def __init__(self):
self.number = 5
test_list = [Test(),Test(),Test()]
writing =open('test_two.py','a')
print(test_list)
writing.write("TestList = {}".format(test_list))
writing.close()
And Here is the Program storing the lists
class Test:
def __init__(self):
self.number = 5
TestList = [<__main__.Test object at 0x103acc690>, <__main__.Test object at 0x103ab38d0>, <__main__.Test object at 0x103b54750>]
However, in the original program, when i try importing i get this error
Traceback (most recent call last):
File "/Users/rudiherrig 1 2/Documents/test.py", line 2, in <module>
from test_two import *
File "/Users/rudiherrig 1 2/Documents/test_two.py", line 4
TestList = [<__main__.Test object at 0x103acc690>, <__main__.Test object at 0x103ab38d0>, <__main__.Test object at 0x103b54750>]
^
SyntaxError: invalid syntax
I have tried searching stack overflow and google for errors when lists have objects in them but could not find anything. Is that even the problem?, I am pretty sure lists can store objects but am not sure. Basically, What do you think is causing the problem?

I noticed the variable names test_list and TestList may refer to the same list, if you change TestList to test_list in your class fine, the error should disappear?
Also, if test_list were a list of strings:
test_list = ['<__main__.Test object at 0x103acc690>', '<__main__.Test object at 0x103ab38d0>', '<__main__.Test object at 0x103b54750>']
the code runs fine, creates test_two.py with these content:
TestList = [<__main__.Test object at 0x000001EE35510588>, <__main__.Test object at 0x000001EE35510508>, <__main__.Test object at 0x000001EE355105C8>]
and prints the same to terminal

Related

types.GenericAlias - subscriptable Types and their use

I was working with namedtuples and learned something that I found odd at first. Still not quite sure how or why this works and what can be the use of this:
from collections import namedtuple
Card = namedtuple('Card', ['rank', 'suit'])
Above code works fine and creates a new Class - Card, which is a subclass of tuple class.
Now when I do this:
newCard = Card('7', 'Hearts')
It serves my purpose of creating a new card. But when I do this:
newCard = Card['7', 'Hearts']
It does not work as expected but also does not throw any error. Normally, Types are not subscriptable and if I try the same with any other class:
class FrenchDeck:
Pass
newDeck = FrenchDeck[1]
It throws following error:
Traceback (most recent call last):
File "C:\Users\sbvik\PycharmProjects\pythonProject\Chapter1.py", line 27, in <module>
c = FrenchDeck[1]
TypeError: 'type' object is not subscriptable
But if I inherit my FrenchDeck class like this:
class FrenchDeck(tuple):
Pass
newDeck = FrenchDeck[1]
No error is thrown.
Then I checked the type of newDeck it turns out to be <class 'types.GenericAlias'>
I am not sure what 'types.GenericAlias' means, what's its purpose and how is it used?
Also, why was TypeError: 'type' object is not subscriptable not thrown in this case?

AttributeError: 'NoneType' object has no attribute 'da'

I am calling another program(script2.py) from the script1.py. The script1.py contains a button when i press it, it will start to execute the script2.py. I want to use a variable of script1 in script2. I have tried 2 way to fetch it but giving the error or the empty list. Please help me with this and let me know if any other information is needed. Thank you.
script1.py
class window2: #i have tried to use d but even the value changes in the __init__function it is giving me a empty list in script2 print function
d=[]
def __init__(data):
self.data=data
window2.d=data
data_copy()
def data_copy(): #so created this function to fetch da but giving the following error
da=window2.d
script2.py
from script1 import data_copy
from script1 import window2
def view():
print(window2.d) #giving empty list
print(data_copy().da) #giving error
Error for data_copy:
Traceback (most recent call last):
File "C:\Users\Desktop\Status\script2.py", line 59, in <module>
view()
File "C:\Users\Desktop\Status\script2.py", line 13, in view
print(data_copy().da)
AttributeError: 'NoneType' object has no attribute 'da'
A common reason you have NoneType where you don't expect it is the assignment of an in-place operation on a mutable object. For example:
mylist = mylist.sort()
The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1),
Python will give you this error.
You can try to create a function in the second script which takes your data as an argument and call it in the first script.
from script2 import view
class Window2:
def __init__(self, data): # init should take self, it is an instance of class
self.data = data
window_2 = Window2('some data') # creating instance
view(window_2.data) # call function from script2
# script2
def view(data):
print(data)
# > 'some data'

About dynamic assignment of attributes in Python 2.x

When I try to dynamically add attributes to instances of object class, I get an AttributeError. However, it is possible do it with instances of subclasses of object.
Does anybody know why?
>>> obj = object()
>>> obj.new_attr = "some value"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'new_attr'
>>> class MyClass(object):
... pass
...
>>> obj = MyClass()
>>> obj.new_attr = "some value"
>>> print obj.new_attr
some value
There is a note in the documentation about that:
http://docs.python.org/3/library/functions.html#object
Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.
There is also a discussion about this on python mailing list:
https://mail.python.org/pipermail/python-list/2011-October/614249.html

What exactly does "AttributeError: temp instance has no attribute '__getitem__'" mean?

I'm trying to understand a problem I'm having with python 2.7 right now.
Here is my code from the file test.py:
class temp:
def __init__(self):
self = dict()
self[1] = 'bla'
Then, on the terminal, I enter:
from test import temp
a=temp
if I enter a I get this:
>>> a
<test.temp instance at 0x10e3387e8>
And if I try to read a[1], I get this:
>>> a[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: temp instance has no attribute '__getitem__'
Why does this happen?
First, the code you posted cannot yield the error you noted. You have not instantiated the class; a is merely another name for temp. So your actual error message will be:
TypeError: 'classobj' object has no attribute '__getitem__'
Even if you instantiate it (a = temp()) it still won't do what you seem to expect. Assigning self = dict() merely changes the value of the variable self within your __init__() method; it does not do anything to the instance. When the __init__() method ends, this variable goes away, since you did not store it anywhere else.
It seems as if you might want to subclass dict instead:
class temp(dict):
def __init__(self):
self[1] = 'bla'

Python: dynamically add attributes to new-style class/obj

Can I dynamically add attributes to instances of a new-style class (one that derives from object)?
Details:
I'm working with an instance of sqlite3.Connection. Simply extending the class isn't an option because I don't get the instance by calling a constructor; I get it by calling sqlite3.connect().
Building a wrapper doesn't save me much of the bulk for the code I'm writing.
Python 2.7.1
Edit
Right answers all. But I still am not reaching my goal; instances of sqlite3.Connection bar my attempts to set attributes in the following ways (as do instances of object itself). I always get an AttributeError:
> conn = sqlite3.connect([filepath])
> conn.a = 'foo'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
conn.a = 'foo'
AttributeError: 'object' object has no attribute 'a'
> conn.__setattr__('a','foo')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
conn.__setattr__('a','foo')
AttributeError: 'object' object has no attribute 'a'
Help?
Yes, unless the class is using __slots__ or preventing attribute writing by overriding __setattr__, or an internal Python class, or a Python class implemented natively (usually in C).
You can always try setting an attribute. Except for seriously weird __setattr__ implementations, assigning an attribute to an instance of a class of one of the types mentioned above should raise an AttributeError.
In these cases, you'll have to use a wrapper, like this:
class AttrWrapper(object):
def __init__(self, wrapped):
self._wrapped = wrapped
def __getattr__(self, n):
return getattr(self._wrapped, n)
conn = AttrWrapper(sqlite3.connect(filepath))
Simple experimentation:
In []: class Tst(object): pass
..:
In []: t= Tst()
In []: t.attr= 'is this valid?'
In []: t.attr
Out[]: 'is this valid?'
So, indeed it seems to be possible to do that.
Update:
But from the documentation: SQLite is a C library that ..., so it seems that you really need to wrap it.
conn.a = 'foo',
or any dynamic assignment is valid, if conn is
<type 'classobj'>.
Things like:
c=object()
c.e=1
will raise an Attribute error. On the otherhand: Python allows you to do fantastic Metaclass programming:
>>>from new import classobj
>>>Foo2 = classobj('Foo2',(Foo,),{'bar':lambda self:'bar'})
>>>Foo2().bar()
>>>'bar'
>>>Foo2().say_foo()
>>>foo

Categories

Resources