Default function parameter is not initialized in Python 3 - python

The following code
def score_track(details, result_details, top_score=200):
if top_score < 120:
# do smth
return None
works in Python 2 but throws exception in Python 3:
Traceback (most recent call last):
File "function.py", line 280, in <module>
search_result.get('score'))
File "ImportList.py", line 131, in score_track
if top_score < 120:
TypeError: '<' not supported between instances of 'NoneType' and 'int'
If I initialize top_score explicitly it goes fine.
score_track function is called like this:
add_song(details,score_track(details,details))
search_result list is constructed like this:
search_results = []
dlog('search details: '+str(details))
lib_album_match = False
if details['artist'] and details['title'] and search_personal_library:
lib_results = [item for item in library if s_in_s(details['artist'],item.get('artist')) and s_in_s(details['title'],item.get('title'))]
dlog('lib search results: '+str(len(lib_results)))
for result in lib_results:
if s_in_s(result['album'],details['album']):
lib_album_match = True
item = {}
item[u'track'] = result
item[u'score'] = 200
search_results.append(item)
What is wrong? I didn't find any information about different behavior of default parameter values in Python3 vs Python2.

Related

Syntax error with exec call to an object in Python 3

I really don't understand what causes the problem, could someone point it out for me please?
with shelve.open(obj_path) as obj:
for as_num in obj['as_number_list']: # ignore warning, obj['as_number_list'] is a list
temp = charge_as(obj['as_' + str(as_num)]) # temp is an object
as_test = temp # doing like this is ok
print(type(as_test))
exec("as_{}_obj = {}".format(as_num, temp)) # **error here**
And it gives syntax error like this:
<class 'instruments.AS'>
Traceback (most recent call last):
File "...", line 45, in <module>
exec("as_{}_obj = {}".format(as_num, temp))
File "<string>", line 1
as_1_obj = <instruments.AS object at 0x000002A86732E290>
^
SyntaxError: invalid syntax
I tried
exec("as_{}_obj = {}".format(as_num, temp.__dict__))
no error is shown but now as_{}_obj is of class 'dict' instead of class 'instruments.AS'
line 45:
exec("as_{}_obj = temp".format(as_num))

Why this Typerror : '>' not supported between instances of 'float' and 'FirefoxWebElement'?

I'm trying to code a script using Python and Selenium, to compare the numbers between value _metal, value_crystal and value_deut with gauss_met_req, gauss_crys_req, and gauss_deut_req.
This error keeps popping up
Traceback (most recent call last):
File "/home/badjorans/Desktop/stob/selenss.py", line 138, in <module>
if value_crystal > gauss_crys_req and value_metal > gauss_met_req and value_deuterium > gauss_deut_req :
TypeError: '>' not supported between instances of 'float' and 'FirefoxWebElement'
I tried to convert the numbers to float but the error keeps appearing.
metal = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[1]/span")
crystal = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[2]/span")
deuterium = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[3]/span")
blackmatter = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[5]/a/span")
energy = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[1]/ul/li[4]/span")
value_metal = float(metal.text)
value_deuterium = float(deuterium.text)
value_crystal = float(crystal.text)
value_energy = int(energy.text)
gauss_met_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[1]/div[2]")
print (gauss_met_req.text)
value_gauss_met = float(gauss_met_req.text)
gauss_crys_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[2]/div[2]")
print (gauss_crys_req.text)
value_gauss_crys = float(gauss_crys_req.text)
gauss_deut_req = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[3]/div[2]/div[1]/form/div/div[2]/div[2]/ul/li[3]/div[2]")
print (gauss_deut_req.text)
value_gauss_deut = float(gauss_deut_req.text)
print(value_metal)
print (value_crystal)
print(value_deuterium)
if value_crystal > gauss_crys_req and value_metal > gauss_met_req and value_deuterium > gauss_deut_req :
print ("we have enough resources to build Gauss Canon")
else:
print ("NOT ENOUGH RESOURCES")
You didn't convert gauss_crys_req, gauss_met_req, and gauss_deut_req to floats like you did with value_crystal, value_metal, and value_deuterium. You seem to already know how to get the text from an element and convert it to a float, so just use the same method for all the variables you are comparing in your conditional.

TypeError: argument of type 'method' is not iterable

Error
Traceback (most recent call last):
File "C:/Users/RCS/Desktop/Project/SHM.py", line 435, in <module>
app = SHM()
File "C:/Users/RCS/Desktop/Project/SHM.py", line 34, in __init__
frame = F(container, self)
File "C:/Users/RCS/Desktop/Project/SHM.py", line 384, in __init__
if "3202" in q:
TypeError: argument of type 'method' is not iterable
code
some part of code, initialisation and all
while 1:
q = variable1.get
if "3202" in q:
variable2.set("NI NODE3202")
try:
switch(labelframe2, labelframe1)
except:
switch(labelframe3, labelframe1)
elif "3212" in q:
variable2.set("NI NODE3212")
try:
switch(labelframe1, labelframe2)
except:
switch(labelframe3, labelframe2)
elif "3214" in q:
variable2.set("NI NODE3214")
try:
switch(labelframe1, labelframe3)
except:
switch(labelframe2, labelframe3)
else:
None
some other part of code
def switch(x, y):
if x.isGridded:
x.isGridded = False
x.grid_forget()
y.isGridded = True
y.grid(row=0, column=0)
else:
return False
I am trying to create a switch between three labelframes which are inside another labelframe, and outside this labelframe are other labelframes that are not changing.
I have read some similar answers but I don't want to use __iter__() in my code. Can anybody provide any other suggestions?
You forgot to call the Entry.get() method:
q = variable1.get()
# ^^ call the method
Because the method object itself doesn't support containment testing directly, Python is instead trying to iterate over the object to see if there are any elements contained in it that match your string.
If you call the method, you get a string value instead. Strings do support containment testing.
The reason you got that error was because you did not add "()" after.get query hence the error to fix this change q = variable1.get to q = variable.get()

Is there a bug in this python module or am I using it the wrong way?

lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.

Python: TypeError: 'str' object is not callable Rating System

When I run this code:
def printPredictions(matches):
pPredictionTable = PrettyTable()
pPredictionTable.field_names = ["Player 1", "Player 2", "Difference", "Winner"]
for match in matches:
p1 = match['teamA']
p2 = match['teamB']
if match['aBeatb'] == True:
pPredictionTable.add_row([match['teamA'], match['teamB'], match['difference'], p1])
else:
pPredictionTable.add_row([match['teamA'], match['teamB'], match['difference'], p2])
print(pPredictionTable)
printPredictions(pmatches)
I get this error:
Traceback (most recent call last):
File "C:\Users\ericr_000\Desktop\PyDev\NPA-2-Rating-System\Rankings.py", line 645, in <module>
printPredictions()
TypeError: 'str' object is not callable
I have pmatches as a separate dictionary, and I don't have the coding skills to fix this issue. (Line 145 is printPredictions(pmatches)
If you're getting 'str' object is not callable when you try to call printPredictions, that means that by the time your program reaches line 645, the name printPredictions was reassigned to a string. Somewhere in your code you have something like
printPredictions = someStringValueGoesHere
You should choose a different name for that variable, or delete the line entirely.
foobar = someStringValueGoesHere

Categories

Resources