Cannot return class attribute from function - function

I would like to get familiar with classes and attributes and defined the following minimal example in the Python console:
class test:
def __init__(self, name):
self.name = name
I initiated a class instance:
>>> first_test = test('Linus')
>>> first_test.name
'Linus'
Works fine. I also tried getattr() to get the value of the attribute:
>>> getattr(first_test, 'name')
'Linus'
No problem. Next, I tried packing getattr() into a function:
def return_name(instance, attribute):
return getattr(instance, attribute)
Again, all fine:
>>> return_name(first_test, 'name')
'Linus'
Now, I wanted to try the same thing with the instance.attribute syntax:
def return_name(instance, attribute):
return instance.attribute
But for some reason, this fails:
>>> return_name(first_test, name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
Another try, this time passing the attribute name as a string:
>>> return_name(first_test, 'name')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in return_name
AttributeError: 'test' object has no attribute 'attribute'
Fail again?
What is the problem here?

Related

Class 'builtins.NoneType' is not mapped

I have face some problem handling the database after certain logic applies.
I have a WTForm that passed the date from a leave application form. Update the LeaveApplication class. And after performing the calculation of the difference between date_to and date_from. I update the LeaveBalance class with the remaining leaves available.
However, i try to simulate this in flask shell session but gotten the error above.
Here's my simulation in the shell session.
> leave = LeaveApplication(user_id='1', leavetype_id='1',
... date_created=datetime.utcnow(),
... date_from=datetime.today() + timedelta(days=3),
... date_to=datetime.today() + timedelta(days=5),
... description='testing')
> db.session.add(leave)
> db.session.commit()
> leave_period = leave.date_to - leave.date_from
> current_leavebalance = LeaveBalance.query.filter_by(user_id='1', leavetype_id=leave.leavetype_id).first()
> updated_leavebalance = current_leavebalance.credits - leave_period.days
> update = LeaveBalance.query.get(leave.id)
> LeaveBalance.credits = updated_leavebalance
> db.session.add(update)
Everything is fine until i perform db.session.add(update) and i received the following traceback
Traceback (most recent call last):
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 2016, in add
state = attributes.instance_state(instance)
AttributeError: 'NoneType' object has no attribute '_sa_instance_state'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 2018, in add
util.raise_(
File "/Users/Ryan/PycharmProjects/LeaveVersion3/venv/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped
I am very new to programming and I am not sure what went wrong despite reading all the existing threads. Would someone explain the problem?

Python3.7 function attribute not available from function object before calling it

def f():
f.created_by = "User1"
pass
f.created_by trows AttributeError: 'function' object has no attribute 'created_by'.
i.e.:
>>> f.created_by
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'created_by
But if I set an attribute externally, is works fine.
i.e.:
>>> f.code = "function code"
>>> f.code
'function code'
>>>
I just want to know why I am able to a set function attribute without calling it, but not able to retrieve another attribute from the same.
The code inside the function only runs when you actually call that function.
So you can do this :
f()
f.created_by
and it will work as you want this bunch of code to work :)

module 'pyarrow' has no attribute 'decimal'

Trying to set the datatype to decimal. I get an error that pyarrow doesn't have the attribute decimal
>>> import pyarrow
>>> pyarrow.decimal(8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'pyarrow' has no attribute 'decimal'
Found that pa.decimal128(18) works

Python Return a list in Bottle

I have a list from an mysql query that I'm trying to return in my bottle website. Is this possible? Here's what I have:
def create_new_location():
kitchen_locations = select_location()
return template('''
% for kitchen_location in {{kitchen_locations}}:
{{kitchen_location}} Kitchen
<br/>
% end''',kitchen_locations=kitchen_locations)
This is the error that I get.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "index.py", line 32, in create_new_location
</form>''',kitchen_locations=kitchen_locations)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3609, in template
return TEMPLATES[tplid].render(kwargs)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3399, in render
self.execute(stdout, env)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 3386, in execute
eval(self.co, env)
File "<string>", line 6, in <module>
TypeError: unhashable type: 'set'
Got It (took me a while...)
% for kitchen_location in {{kitchen_locations}}:
Should be
% for kitchen_location in kitchen_locations:
When using the % at the beginning you don't need the {{}}.
This error:
TypeError: unhashable type: 'set'
is trying to use a set literal {{kitchen_locations}} ==>
kitchen_locations in a set in another set. since set is not hash-able you got the error

web2py: module function that behaves normally in shell fails browser mode

I have a very simple helper function that helps creates column definitions for a javascript framework I"m using.
def tocol(fields,title=None,width=None,attributes=None):
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
cols["field"] = fields
return cols
when I try this in a web2py shell the result is as I'd expect:
In [15]: col = tocol(attr.columns.tolist())
In [16]: col
Out[16]: {'field': ['l1', 'pw', 'bw', 'tilt']}
but when I try the same thing in a view I get the following traceback:
Traceback (most recent call last):
File "/home/tahnoon/web2py/gluon/restricted.py", line 224, in restricted
exec ccode in environment
File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 788, in <module>
File "/home/tahnoon/web2py/gluon/globals.py", line 392, in <lambda>
self._caller = lambda f: f()
File "/home/tahnoon/web2py/applications/apollo/controllers/performance.py", line 561, in pa_equity
cols = tocol(attr.columns.tolist())
File "applications/apollo/modules/helpers.py", line 33, in tocol
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
File "applications/apollo/modules/helpers.py", line 33, in <genexpr>
cols = dict((name,eval(name)) for name in ['title','width','attributes'] if eval(name) is not None)
File "<string>", line 1, in <module>
NameError: name 'title' is not defined
Might anyone have any idea what is going wrong here? Pretty mystified.
Thanks
It looks like you're just trying to remove None values from a dictionary, so instead, why not just create a function to do that:
def remove_none(d):
[d.pop(key) for key in d.keys() if d[key] is None]
Then you can do:
col = remove_none(dict(field=attr.columns.tolist(),
title=None, width=None, attributes=None))
Or if you want to enter the arguments directly::
def remove_none_dict(**d):
[d.pop(key) for key in d.keys() if d[key] is None]
return d
col = remove_none_dict(field=attr.columns.tolist(),
title=None, width=None, attributes=None))