python3 object has no attriubute - python-3.x

I have a file called entities.py, which contains the following code:
class EntityClass:
entities = {}
def __init__(self, parent=None):
.......
def show_all(self):
......
But then, when I run python 3 and type the command as follows:
>>> import entities
>>> ent = entities.EntityClass()
>>> ent.show_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'EntityClass' object has no attribute 'show_all'
show_all should clearly be an attribute for EntityClass.
This of course worked perfectly in Python 2, and I'm assuming it's a Python 3 issue...
Is there a work around for this?

From the code posted, it looks like your indentation levels are wrong, you have declared the show_all() method on the module, not the class.
def_show_all(self): Should be indented to the same level as entities = {}
class EntityClass:
entities ={}
def __init__(self,parent=None):
.......
def show_all(self):
......

Related

Why can't I pickle my custom exception in Python

I am using Python 3.6. I defined a custom exception following this page: https://docs.python.org/3.6/tutorial/errors.html
class MyException(Exception):
def __init__(self, a):
self.a = a
Now, if I try to pickle + unpickle this exception, I get the following error:
>> e = MyException(a=1); pickle.loads(pickle.dumps(e))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-413e2ac6234d> in <module>
----> 1 e = MyException(a=1); pickle.loads(pickle.dumps(e))
TypeError: __init__() missing 1 required positional argument: 'a'
Does anyone know why?
Seems to be that the Exception baseclass has special treatment for named arguments (likely in its implementation of __new__)
you can fix this by properly calling the base class in your __init__ method:
>>> class MyException(Exception):
... def __init__(self, a):
... super().__init__(a)
... self.a = a
...
>>> pickle.loads(pickle.dumps(MyException(a=1)))
MyException(1,)

How to Persist class Instances using klepto

I'm trying klepto as a replacement for shelve to persist class instances but am seeing a lengthy traceback when attempting to do so.
My platform is:
python 3.7.3
klepto 0.1.6
The example #
Pickle versus shelve storing large dictionaries in Python
... works fine on the above platform.
from dataclasses import dataclass
#dataclass (frozen=True)
class Target:
name : str
#dataclass (frozen=True)
class Image:
target :Target
image_1 = Image (target=Target(name='Crab Nebula'))
image_2 = Image (target=Target(name='Orion Nebula'))
##keys = image_1.name, image_2.name
keys = image_1.target.name, image_2.target.name
values = image_1, image_2
d = dict ( zip (keys,values))
import klepto
a = klepto.archives.dir_archive (dict=d)
a.dump()
a.dump() initiates a lengthy traceback beginning with ...
File "C:\Users\jgv\Documents\Projects\AstroPix_ODB (klepto)\stackoverflow.py", line 20, in <module>
a.dump()
File "C:\Users\jgv\AppData\Local\Programs\Python\Python37\lib\site-packages\klepto\_archives.py", line 165, in dump
self.archive.update(self)
and concluding with ...
File "C:\Users\jgv\AppData\Local\Programs\Python\Python37\lib\site-packages\dill\_dill.py", line 1148, in save_dictproxy
raise ReferenceError("%s does not reference a class __dict__" % obj)
ReferenceError: {} does not reference a class __dict__

How do I bind a member_descriptor to a class without a reference in class.__dict__

Since my privatization trick works in both IDLE and the python3 REPL:
>>> class A(object):
... __slots__ = ['attr']
...
>>> dscget = A.__dict__['attr'].__get__
>>> dscset = A.__dict__['attr'].__set__
>>> del A.attr
>>>
but not quite in my program (same exact setup and mechanics)
Python 3.4.3 |Anaconda 2.3.0 (32-bit)| (default, Mar 6 2015, 12:08:17) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "\home\tcll\Projects\python\UGE\test_FORMAT.py", line 5, in <module>
import API
File "\home\tcll\Projects\python\UGE\API\__init__.py", line 43, in <module>
from . import CONST, OBJECT
File "\home\tcll\Projects\python\UGE\API\OBJECT\__init__.py", line 191, in <module>
from ._collection import *
File "\home\tcll\Projects\python\UGE\API\OBJECT\_collection.py", line 209, in <module>
private()
File "\home\tcll\Projects\python\UGE\API\OBJECT\_collection.py", line 187, in private
getbase, setbase = getset( UGECollection, '__base__' ); del UGECollection.__base__
AttributeError: readonly attribute
>>>
I should note this is actually the 3rd class that loads, the first 2 classes actually work as expected and load without issue, though they don't delete the attributes, only overwrite them with read-only properties.
I want to know how member_descriptor is initialized and registered to the class so I can look into creating them without the need for a reference in the class dict.
the member_descriptor name can be obtained easily, but instance creation seems very difficult:
>>> class A(object):
... __slots__ = ['attr']
...
>>> member_descriptor = A.attr.__class__
>>> member_descriptor()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
member_descriptor()
TypeError: cannot create 'member_descriptor' instances
>>> member_descriptor.__new__(member_descriptor)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
member_descriptor.__new__(member_descriptor)
TypeError: object.__new__(member_descriptor) is not safe, use member_descriptor.__new__()
>>>
I'm pretty sure it's impossible to do it through python, but how can I do it through something like ctypes or cffi??
Well, creating a member_descriptor outside of a defined class isn't exactly possible since a __slots__ class is basically a C struct{}, where the member_descriptor instance is basically a wrapper that handles a pointer to the struct instance...
and as I understand, you can't modify an existing struct definition...
so I ultimately decided on using an alternate privatized class as a workaround for storing the private attributes like so:
def private():
privateRegistry = {} # as long as I don't need access to private attributes within __hash__ it won't infinitely recurse
getprivate = privateRegistry.__getitem__; setprivate = privateRegistry.__setitem__ # just for quick access
class privateAttrs(object):
__slots__ = ['a']
get_a, set_a = getset( privateAttrs, 'a', privatize=False ) # just for quick access
new = object.__new__
class Object(object):
__slots__ = ['public']
def __new__(cls):
i = new(cls)
p = new(privateAttrs); setprivate( i, p )
set_a( p, 15 ) # p.a = 15 with no dot operator slowness since you're calling __set__ directly
def __getitem__(i, item):
p = getprivate(i)
return get_a(p)
return Object
Object = private()
del private
Something I find funny though...
Out of about 15 classes I'm privatizing in the same manner as UGECollection above, UGECollection is the only offender...
EDIT: Also, I know this isn't truely private, but it's better than __not_so_private attributes...
you can pick any one of Object's methods to gain access to specific getters and setters of the private attributes (or the private class itself in this case) from __closure__ (despite knowing it's possible to write to read-only properties), but there's a level of security from that which I'm comfortable with since cells are indexed rather than keyed and you can't expect cells to remain in the same order (if at all) with an active project.

SQLAlchemy 1.2 AttributeError: 'list' object has no attribute 'Session'

I was trying to use the code snippet from this tutorial:
http://newcoder.io/scrape/part-4/
The following is the file with the class definition:
from sqlalchemy.orm import sessionmaker
from .models import Deals, db_connect, create_deals_table
class Test(object):
def __init__(self, args):
"""
Initializes database connection and sessionmaker.
Creates deals table.
"""
engine = db_connect()
create_deals_table(engine)
self.Session = sessionmaker(bind=engine)
def add_item(self):
session = self.Session()
tester = Deals(title="test 3 deal",location='here', price=2.00)
session.add(tester)
session.commit()
When I call Test.add_item(args), the following error is generated.
(sql) [bucket#localhost heap]$ python heap.py test Traceback (most
recent call last): File "heap.py", line 13, in <module>
main(sys.argv) File "heap.py", line 8, in main
Test.add_item(args) File "/home/bucket/src/heap/game/engine.py", line 17, in add_item
session = self.Session() AttributeError: 'list' object has no attribute 'Session'
The code worked fine and added a row when I ran the the same code as a python script with no class definition.
You're trying to call an instance method on the class itself: Test.add_item(args)
You define the method as only having self and no parameters. This means that you need to call it on an instance of the class, and pass it no arguments
test = Test()
test.add_item()
The reason you're getting that particular error is because you're calling the function with the list argument args getting used as the parameter self, and then the self.Session() line is attempting to get the attribute Session from the args object. You need to fix either the method definition or your call to it (e.g., def add_item(self, args):)

Utilizing collections module in Python 3

Relatively pointed question. Currently running Python 3.4.1 and am just working on an object-orientated exercise where I need to overwrite some functions from an inherited class.
Goal:
importing from builtin module collections and utilizing collections.UserList rewrite the append, extend so that it will not "add" any duplicates if detected. (this part accomplished)
Problem:
The main problem is that I still am learning object oriented programming and I want to build objects which can be easily typed in and returned so I am writing a str and repr for my class
Currently my class looks like the below: (omitted the "goal" stuff because it works)
import collections
class UList (collections.UserList):
def __init__(self, entry =[]):
self.entry = entry
def __str__ (self):
print (self.entry)
return
def __repr__(self):
return self.__str__()
Then I decide to run some sample code for good measure:
>>> x = UList ([4,5,6])
>>> x.entry
[4, 5, 6]
>>> x
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x
TypeError: __repr__ returned non-string (type NoneType)
>>> print(x)
[4, 5, 6]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print(x)
TypeError: __str__ returned non-string (type NoneType)
usually I look straight to the objects and try to figure out what went wrong but I am a little confused as I am still new =(. Can someone help explain why it is returning a NoneType even after I have overwritten the init? (also, a possible solution on how I can rectify so no error would be extremely helpful)
Consider (note no explicit return at the end of __str__) :
>>> class Foo:
... def __str__(self):
... print('Foo!!')
...
>>> f=Foo()
>>> f
<__main__.Foo object at 0x10a655080>
>>> print(f)
Foo!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type NoneType)
Vs:
>>> class Foo:
... def __str__(self):
... return 'Foo!!!'
...
>>> f=Foo()
>>> print(f)
Foo!!!
The issue is that __repr__ and __str__ need to return a return a string. The return from __repr__ should, if possible, be the 'official' string representation of the object for eval to recreate the object or some other <useful definition> according the the docs on __repr__
The docs on __str__ a more convenient or concise representation can be used' other than a Python expression.

Resources