How to add definition modules? - python

I'm completing a task I was given by my Teacher and it asks for a modular program so I tried to create some def modules but I can't figure out how to pass parameters between them.
Here's the code so far. (I don't know how to make it much neater on the site sorry.)
import string
def Datawrite ():
forename = []
surname = []
distance = []
data = open("members.txt","r")
for line in data:
value = line.split(',')
forename.append(value[0])
surname.append(value[1])
distance.append(value[2])
data.close()
def FarthestWalker(distance):
farthest_walk = distance[0]
for counter in range(len(distance)):
if float(distance[counter]) >= float(farthest_walk):
farthest_walk = distance[counter]
farthest_walk = float(farthest_walk)
Calcandstore()
def Calcandstore(forename,surname,distance,farthest_walk):
Results = open("Results.txt","w+")
Results.write("The prize winnning memberes are:\n")
seventy = 0.7*farthest_walk
Winning = []
for count in range(len(distance)):
if float(distance[count]) >= float(seventy):
Winning.append([count])
for count in range(len(Winning)):
Results.write(forename[count]+":")
Results.write(surname[count]+":")
Results.write(distance[count])
Results.close()
Datawrite()
FarthestWalker(distance)
Calcandstore(forename,surname,distance,farthest_walk)
When I run the code it returns this.
Traceback (most recent call last):
File "E:\Assignment\Test.py", line 58, in <module>
FarthestWalker(distance)
File "E:\Assignment\Test.py", line 29, in FarthestWalker
farthest_walk = distance[0]
IndexError: list index out of range
I have been tinkering with this for a few days now and I can't get the thing to work.

Here are some issues:
1) Datawrite doesn't return anything so the lists you're building are lost in the ether.
2) You call FarthestWalker with distance which is never initialized.
3) You call Calcandstore with values that are not initialized.
To pass values from functions you need to return values and declare them. For example:
def make_cat():
return 'Cat'
def print_animal(animal):
print(animal)
c = make_cat()
print_animal(c)

Related

Required positional argument: 'self', when loading from list

Im trying to load the data from a list in python where, I save the data in a list:
class Region(object):
def __init__(self, cities: list[CitiySalah], label: str):
self.cities = cities
self.label = label
def toMap(self) -> dict:
map = self.__dict__
r = [{}]
for x in self.cities:
r.append(x.toMap())
map["cities"] = r
return map
and the one that loads the data is:
def startLoading() -> list[Region]:
.......
for select in selects:
if select.has_attr("name") and select['name'] == "ville":
groups = select.find_all('optgroup')
for group in groups:
lable = group['label']
allR = {"lable": lable}
cities = [CitiySalah]
for option in group:
try:
# the city
if(option.has_attr('value')):
value = option['value']
city = str(option).split('<')[1].split('>')[1]
id = str(option).split('<')[1].split(
'?ville=')[1].split('"')[0]
dataUrl = url+"?ville="+id
data = MySalah(getSalahHour(dataUrl))
R = CitiySalah(argu={"value": value,
"city": city,
"dataUrl": dataUrl,
"id": id, }, data=data)
# print(R.toMap())
cities.append(R)
except:
pass
# allR['cities'] = cities
res.append(Region(label=lable, cities=cities))
return res
and when I'm trying to call the function by:
def getDataForDatabase():
listR = [{}]
data = startLoading()
for x in data:
listR.append(x.toMap())
return listR
I get this error
Traceback (most recent call last):
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 108, in <module>
print(getDataForDatabase())
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 104, in getDataForDatabase
listR.append(x.toMap())
TypeError: toMap() missing 1 required positional argument: 'self'
I have tried, I'm still new in python as I'm from c++ family, and I got stuck here,
I need to save the data in a list and convert them into Map, so I can save them in the database (NoSQL).
and as for the rest of models they are working correct, I don't know why I'm getting this error.

KeyError Dictionary Conversion Python

I would like to create a program that converts money from one type of currency to another. So far this is my code:
def read_exchange_rates(exchange_file_name):
#reads file with exchange rates formatted like USD,1. Each line is a 3 letter currency code and a float to convert it to USD.
f=open(exchange_file_name,"r")
answer={}
for line in f:
k, v = line.split(",")
answer[k] = float(v)
return answer
f.close()
pass
class Money:
exchange_rates = read_exchange_rates(rate_file)
#calls previously defined function to read file with exchange rates
def __init__ (self, monamount, code):
self.monamount=monamount
self.code=code
def to(self, othercode):
i = self.monamount/self.exchange_rates[self.code]
j = i*self.exchange_rates[self.othercode]
return othercode+str(j)
It should return the converted amount along with it's currency code (othercode) but instead it returns a KeyError. If I type
a=Money(650,'USD')
b=a.to('GBP')
it should return GBP somenumber. This is the error. Thank you!
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
b=a.to('GBP')
File "<pyshell#124>", line 9, in to
i = self.monamount/self.exchange_rates[self.code]
KeyError: 'USD'
Are you sure your file contains 'USD' key?
Here is a slightly modified and simplified code (so I didn't have to create an exchange file):
def read_exchange_rates():
answer={}
answer['USD'] = 1
answer['GBP'] = 0.76
return answer
class Money:
exchange_rates = read_exchange_rates()
def __init__ (self, monamount, code):
self.monamount = monamount
self.code = code
def to(self, othercode):
i = self.monamount/self.exchange_rates[self.code]
j = i*self.exchange_rates[othercode]
return othercode + str(j)
a = Money(650,'USD')
b = a.to('GBP')
print(b)
This prints out GBP494.0.

sqlalchemy.exc.InvalidRequestError: Can't attach instance another instance with key is already present in this session

Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a solution :( . I pasted as much code as I could so you could see
Traceback (most recent call last):
File "/home/scwall/PycharmProjects/purebeurre/recovery.py", line 171, in <module>
connection.connect.add(article)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1776, in add
self._save_or_update_state(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1796, in _save_or_update_state
self._save_or_update_impl(st_)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2101, in _save_or_update_impl
self._update_impl(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2090, in _update_impl
self.identity_map.add(state)
File "/home/scwall/PycharmProjects/purebeurre/venv/lib/python3.6/site-packages/sqlalchemy/orm/identity.py", line 149, in add
orm_util.state_str(state), state.key))
sqlalchemy.exc.InvalidRequestError: Can't attach instance <Categories at 0x7fe8d8000e48>; another instance with key (<class 'packages.databases.models.Categories'>, (26,), None) is already present in this session.
Process finished with exit code 1
class CategoriesQuery(ConnectionQuery):
#classmethod
def get_categories_by_tags(cls, tags_list):
return cls.connection.connect.query(Categories).filter(Categories.id_category.in_(tags_list)).all()
other file:
def function_recovery_and_push(link_page):
count_and_end_page_return_all = {}
count_f = 0
total_count_f = 0
list_article = []
try:
products_dic = requests.get(link_page).json()
if products_dic['count']:
count_f = products_dic['page_size']
if products_dic['count']:
total_count_f = products_dic['count']
if not products_dic['products']:
count_and_end_page_return_all['count'] = False
count_and_end_page_return_all['total_count'] = False
count_and_end_page_return_all['final_page'] = True
else:
count_and_end_page_return_all['final_page'] = False
for product in products_dic["products"]:
if 'nutrition_grades' in product.keys() \
and 'product_name_fr' in product.keys() \
and 'categories_tags' in product.keys() \
and 1 <= len(product['product_name_fr']) <= 100:
try:
list_article.append(
Products(name=product['product_name_fr'], description=product['ingredients_text_fr'],
nutrition_grade=product['nutrition_grades'], shop=product['stores'],
link_http=product['url'],
categories=CategoriesQuery.get_categories_by_tags(product['categories_tags'])))
except KeyError:
continue
count_and_end_page_return_all['count'] = count_f
count_and_end_page_return_all['total_count'] = total_count_f
list_article.append(count_and_end_page_return_all)
return list_article
except:
count_and_end_page_return_all['count'] = False
count_and_end_page_return_all['total_count'] = False
count_and_end_page_return_all['final_page'] = True
list_article.append(count_and_end_page_return_all)
return list_article
p = Pool()
articles_list_all_pool = p.map(function_recovery_and_push, list_page_for_pool)
p.close()
for articles_list_pool in articles_list_all_pool:
for article in articles_list_pool:
if type(article) is dict:
if article['count'] != False and article['total_count'] != False:
count += article['count']
total_count = article['total_count']
if article['final_page'] is True:
final_page = article['final_page']
else:
connection.connect.add(article)
I receive this as an error message, thank you in advance for your answers
This error happens when you try to add an object to a session but it is already loaded.
The only line that I see you use .add function is at the end where you run:
connection.connect.add(article)
So my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a try, except and rollback the operation if it throws an exception.
Had the same issue, not sure you implemented the models as same as I did, but in my case at least, I had in the table's model - i.e:
product_items = relationship(...)
So later when I tried to do
products = session.query(Products).all()
one_of_the_products = products[0]
new_product = ProductItem(product_id=one_of_the_products.id, name='foo', category='bla')
session.add(new_product)
It raises the same exception as you:
sqlalchemy.exc.InvalidRequestError: Can't attach instance <ProductItem at 0x7fe8d8000e48>; another instance with key (<class 'packages.databases.models.ProductItem'>, (26,), None) is already present in this session.
The reason for the exception, is that when I queried for products - the relationship created it's own sub-query and attached the product_item's objects, it placed them in the variable name I defined in the relationship() -> product_items.
So instead of doing:
session_add(new_product)
I just had to use the relationship:
one_of_the_products.product_items.append(new_product)
session.commit()
hope it helps others.
unloading all objects from session and then adding it again in session might help.
db.session.expunge_all()
db.session.add()

list index out of range in heroku/phython - trying to follow guide to code

I'm trying to follow this guide: https://medium.com/#sarahnadia/how-to-code-a-simple-twitter-bot-for-complete-beginners-36e37231e67d#.k2cljjf0m
This is the error message:
MacBook-Pro-2:heroku_ebooks-master Rupert$ heroku run worker
Running worker on ⬢ desolate-brushlands-56729... up, run.6788
Traceback (most recent call last):
File "ebooks.py", line 79, in <module>
source_tweets_iter, max_id = grab_tweets(api,max_id)
File "ebooks.py", line 51, in grab_tweets
max_id = user_tweets[len(user_tweets)-1].id-1
IndexError: list index out of range
This is the code:
def grab_tweets(api, max_id=None):
source_tweets=[]
user_tweets = api.GetUserTimeline(screen_name=user, count=200, max_id=max_id, include_rts=True, trim_user=True, exclude_replies=True)
max_id = user_tweets[len(user_tweets)-1].id-1
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
if __name__=="__main__":
order = ORDER
if DEBUG==False:
guess = random.choice(range(ODDS))
else:
guess = 0
if guess == 0:
if STATIC_TEST==True:
file = TEST_SOURCE
print ">>> Generating from {0}".format(file)
string_list = open(file).readlines()
for item in string_list:
source_tweets = item.split(",")
else:
source_tweets = []
for handle in SOURCE_ACCOUNTS:
user=handle
api=connect()
max_id=None
for x in range(17)[1:]:
source_tweets_iter, max_id = grab_tweets(api,max_id)
source_tweets += source_tweets_iter
The traceback tells us the error is here:
max_id = user_tweets[len(user_tweets)-1].id-1
which will be out of range if user_tweets is an empty list. You can check to make sure it isn't before trying to access its value.
if len(user_tweets) > 0:
max_id = user_tweets[-1].id-1
Note the use of user_tweets[-1]. Using a negative index counts backward from the end, so the last element of a list is always at [-1].

RuntimeError: maximum recursion depth exceeded (without an explicit recursive call in my Python code)

I am trying to read key-value pairs from an already existing shelf to create a new class object with a updated field and write that class object to a new shelf.
My class object : SongDetails
This is the procedure which fails:
def updateShelfWithTabBody(shelfFileName, newShelfFileName):
"""this function updates songDetails with
html body i.e. just the part that contains lyrics and
chords in the tab """
#read all songDetails
shelf = shelve.open(shelfFileName)
listOfKeys = shelf.keys()
#create new songDetails object
temporaryShelfObject = SongDetails.SongDetails()
#iterate over list of keys
for key in listOfKeys:
#print "name:"+shelf[key].name
#fill details from temporaryShelfObject
temporaryShelfObject.name = shelf[key].name
temporaryShelfObject.tabHtmlPageContent = shelf[key].tabHtmlPageContent
#add new detail information
htmlPageContent = shelf[key].tabHtmlPageContent
temporaryShelfObject.htmlBodyContent = extractDataFromDocument.fetchTabBody(htmlPageContent)
#write SongDetails back to shelf
writeSongDetails.writeSongDetails(temporaryShelfObject, newShelfFileName)
Definitions for functions used in above code:
def fetchTabBody(page_contents):
soup = BeautifulSoup(page_contents)
HtmlBody = ""
try:
#The lyrics and chords of song are contained in div with id = "cont"
#Note: This assumtption is specific to ultimate-guitar.com
HtmlBody = soup.html.body.find("div",{"id":"cont"})
except:
print "Error: ",sys.exc_info()[0]
return HtmlBody
def writeSongDetails(songDetails, shelfFileName):
shelf = shelve.open(shelfFileName)
songDetails.name = str(songDetails.name).strip(' ')
shelf[songDetails.name] = songDetails
shelf.close()
SongDetails class:
class SongDetails:
name = ""
tabHtmlPageContent = ""
genre = ""
year = ""
artist = ""
chordsAndLyrics = ""
htmlBodyContent = ""
scale = ""
chordsUsed = []
This is the error that I get:
Traceback (most recent call last):
File "/l/nx/user/ndhande/Independent_Study_Project_Git/Crawler/updateSongDetailsShelfWithNewAttributes.py", line 69, in <module>
updateShelfWithTabBody(shelfFileName, newShelfFileName)
File "/l/nx/user/ndhande/Independent_Study_Project_Git/Crawler/updateSongDetailsShelfWithNewAttributes.py", line 38, in updateShelfWithTabBody
writeSongDetails.writeSongDetails(temporaryShelfObject, newShelfFileName)
File "/home/nx/user/ndhande/Independent_Study_Project_Git/Crawler/writeSongDetails.py", line 7, in writeSongDetails
shelf[songDetails.name] = songDetails
File "/usr/lib64/python2.6/shelve.py", line 132, in __setitem__
p.dump(value)
File "/usr/lib64/python2.6/copy_reg.py", line 71, in _reduce_ex
state = base(self)
File "/u/ndhande/.local/lib/python2.6/site-packages/BeautifulSoup.py", line 476, in __unicode__
return str(self).decode(DEFAULT_OUTPUT_ENCODING)
**RuntimeError: maximum recursion depth exceeded**
I couldn't find any reason why I'm getting this error even though there is no explicit recursive call in my code. I have seen this error in other stackoverflow posts, but they did have recursive calls in their case.
str(self) calls __str__ or calls __unicode__ calls str(self).

Categories