I am using flask. When I do not pass StartingSequenceNumber to flask app then How can I handle null object.
class Meta():
def __init__(self, j):
self.__dict__ = json.loads(j)
in bootstrap.py
meta = Meta(request.get_data().decode())
if meta.StartingSequenceNumber is not None:
# do something
Error : AttributeError: 'Meta' object has no attribute 'StartingSequenceNumber'
You could use the hasattr() built-in function (https://docs.python.org/3/library/functions.html#hasattr) which will return True if the object has the attribute :
if hasattr(object, 'attribute'):
# do smthg
else:
# do smthg else
But it would be better to used try & except blocks and throw an AttributeError
try:
doSmthg()
except AttributeError:
# do smthg else
Related
I wondered wheather it is actually impossible to make a protected python class, there always seems to be a way of getting around that, but i can't find one for this:
I attempted to code out this properly encapsulated class. Challenge:
Attempt setting somevalue to the value 69, without:
changing the code from line 1 - 32
polymorphism
from sbNative.debugtools import log # module not neccessary, only for logging and debugging purposes imported
from inspect import stack
import traceback
class Protected:
def __init__(self):
self._somevalue = "Unset"
log(self._somevalue)
def __setattr__(self, name, value):
if isinstance(stack()[1][0].f_locals.get("self"), Protected) or not name.startswith("_"):
super(Protected, self).__setattr__(name, value)
else:
raise AttributeError("Protected class from setting")
def __getattribute__(self, name):
if isinstance(stack()[1][0].f_locals.get("self"), Protected) or not name.startswith("_"):
return super(Protected, self).__getattribute__(name)
else:
raise AttributeError("Protected class from getting")
#property
def somevalue(self):
return self._somevalue
#somevalue.setter
def somevalue(self, value):
if value == 69:
raise ValueError(f"{value} is an illegal value.")
self._somevalue = value
log("Instantiates without a problem:")
p = Protected()
print("\n")
log("Fails because it is not allowed to set to this value:")
try:
p.somevalue = 69
except ValueError:
traceback.print_exc()
print("\n")
log("Fails because it attemps setting and getting directly:")
try:
p._somevalue = 69
except AttributeError:
traceback.print_exc()
print("")
try:
log(p._somevalue)
except AttributeError:
traceback.print_exc()
print("\n")
log("Succeeds because it is allowed to set and get this value:")
p.somevalue = 420
log(p.somevalue)
print("ⁿᶦᶜᵉ ˡᶦⁿᵉ ⁿᵘᵐᵇᵉʳ ᵇᵗʷ")
I have written this code by defining instSet() class (This code inserts element to list using insert() method and then performs various functions such as removing an element using remove() method by checking if the element is present, if not, raises an expetion:
class instSet(object):
def __init__(self):
self.vals = []
def insert(self, e):
if not e in self.vals:
self.vals.append(e)
def remove(self, e):
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def member(self, e):
return e in self.vals
def __str__(self):
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}'
Some expression performed are:
a = instSet()
a.insert(1)
a.remove(3)
print(a)
Main problem is when I am trying to remove an element which is not present in the list it is throwing error like this:
ValueError: list.remove(x): x not in list
Insted it should return:
ValueError: 3 not found
What is wrong in the above code?
There is issue with valueError that you used in except. Try using below code
except:
raise Exception(str(e) + ' not found') from None
Selenium w/Python3 class_status = like.get_attribute("class") AttributeError: 'str' object has no attribute 'get_attribute' facing this issue
I am facing this issue when I call the first function is called but the number 2 function is not working
class Like():
def __init__(self,video_xpath,like_refiq):
self.video_xpath = video_xpath
self.like_refiq=like_refiq
# self.dislike=dislike
def like_dislike(self):
like =self.video_xpath
time.sleep(5)
# count = like.text
class_status = like.get_attribute("class")
if class_status == "selected":
like.click()
time.sleep(3)
# alredy_like_cls_status = like.get_attribute("class")
alredy_count = like.text
return print(f"creation un{alredy_count} {self.like_refiq} count")
elif class_status == "":
like.click()
time.sleep(3)
# non_like_cls_status = like.get_attribute("class")
non_count = like.text
return print(f"creation {non_count} {self.like_refiq} count")
else:
assert False
class Refiq(Like):
pass
like_path=driver.find_element_by_xpath("//w-creation-detail-popup//li[1]//a[1]")
Like_dislike=Like(video_xpath=like_path,like_refiq="like")
Like_dislike.like_dislike()
# like dislike function call
refq_unfrefiq=Refiq(video_xpath="//w-creation-detail-popup//li[2]//a[1]",like_refiq="refiq")
refq_unfrefiq.like_dislike()
You have assigned the like variable a string by like =self.video_xpath.
So, it's correct, click is a sting and you can't apply .get_attribute("class") on string object.
click is not a webelement object.
I'm trying to display linked list elements in the form of a list but keep getting this error:
AttributeError: 'NoneType' object has no attribute 'data'
class Node:
def __init__(self,data=None,next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self,data):
node = Node(data,self.head)
self.head = node
def display(self):
elements = []
currNode = self.head
while currNode:
currNode = currNode.next
elements.append(currNode.data)
print(elements)
if __name__ == "__main__":
ll = LinkedList()
ll.insert_at_beginning(1)
ll.insert_at_beginning(2)
ll.insert_at_beginning(3)
ll.display()
Can anyone explain the error here?
After the while loop, append data first then go to the next. You're getting the error because if currNode.next is null then it's showing the object has no attribute 'data'. So, append first then go to next. If currNode.next is null then the loop will stop.
while currNode:
elements.append(currNode.data)
currNode = currNode.next
I have a class with an attribute which has to be set only once (let us say via a command line parameter). From there on it is not to be changed.
class Example(object):
_classattribute = None
I am doing this by reading the command line param, and passing them as parameters during object construction. Depending on the classatribute, I return a different object Type.
class Example(object):
_classattribute = None
_instance = None
def __new__(cls, attribute=None):
if not cls._clsattribute:
if not attribute:
raise ValueError('class attribute not set')
cls._clsattribute = attribute
if cls._classatribute == condition1:
cls._instance = Type1(cls._classattribute)
if cls._classatribute == condition2:
cls._instance = Type2(cls._classattribute)
return cls._instance
class Type1:
def __init__(self, property):
self.property = property
class Type2:
def __init__(self, property):
self.property = property
During the object construction, for the very first time:
eg1 = Example("This is type1 attribute")
Subsequent construction of the object:
eg2 = Example()
Is this a good approach I can't say. It feels too explicit to me. Besides it is similar to the Borg, shared state pattern, except for the one time setting of the class attribute _claassattribute.
Any form of critique/feedback/thought/suggestion is welcome.
This is something of a personal design choice, but my take on this is that __new__ should always return an object of the class or None. In your code, there is no reason to use a class if it can never return an instance of its own. What you probably want ressembles a factory that returns either objects of Type1 or Type2.
def get_type_factory(attribute):
if attribution == condition1:
return lambda: Type1(attribute)
elif attribute == condition2:
return lambda: Type2(attribute)
else:
raise ValueError
# Can be used like so
factory = get_type_factory('foo')
type_object1 = factory()
type_object2 = factory()