Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've got a function get_prefix_lists with returns two values, each is a list of strings.
I then want to use those lists separately in another function. My code below is how i've done it but it feels dirty to use the same variable name (prefixes) in the __main__ section.
Is there a less dirty way?
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
v4_prefixes = []
v6_prefixes = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
v4_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
v4_prefixes.append(result.prefix)
else:
v6_prefixes.append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
v6_prefixes.append(result.prefix)
return v4_prefixes, v6_prefixes
def get_radb_prefixes(prefixes):
for prefix in prefixes:
r = requests.get(url=radb_url + 'route/' + prefix + 'AS11111?password=' + radb_mnt_password, headers=headers)
if r.status_code == 200:
pass
elif r.status_code == 404:
print(f"{prefix} Is in NetBox but not RADB")
else:
print(r.status_code, r.text)
if __name__ == "__main__":
print("V4 check")
prefixes = get_radb_prefixes(get_prefix_lists()[0])
print("V6 check")
prefixes = get_radb_prefixes(get_prefix_lists()[1])
Why not returning a dictionary?
{"v4": [], "v6": []}
Here's just some quickly jotted code to better explain:
def get_prefix_lists():
""" Get prefixes from netbox with site-aggregate role """
prefixes = {}
prefixes['v4'] = []
prefixes['v6'] = []
for aggregate in nb.ipam.aggregates.filter(rir=['arin','ripe']):
if aggregate.family == 4:
prefixes['v4'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=4, role='aggregate', within_include=aggregate.prefix):
prefixes['v4'].append(result.prefix)
else:
prefixes['v6'].append(aggregate.prefix)
for result in nb.ipam.prefixes.filter(family=6, role='aggregate', within_include=aggregate.prefix):
prefixes['v6'].append(result.prefix)
return prefixes
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Why does it say 'Die eingegebenen Daten haben den falschen Datentyp!' when the datatypes are actually right? Doesn't even work with just matrNr... Although I checked my input of matrNr to be an int?!
class Student:
def __init__(self):
self.matrNr = -1
self.vorname = ''
self.nachname = ''
self.gebDatum = []
self.email = ''
self.telNr = ''
def DatenUebergeben(self, matrNr, vorname, nachname, gebDatum, telNr):
if matrNr == int and vorname == str and nachname == str and gebDatum == list and telNr == str:
print('richtige Datentypen!')
else:
print('Die eingegebenen Daten haben den falschen Datentyp!')
student1 = Student()
student1.DatenUebergeben(12345,'linda','f',[2,2,1995],'12345')
Background
By checking (for example) matrNr == int you actually compare the variable matNr, which is an int (an instance of <class 'int'>) to the class int (<class 'int'>).
Quick fix
You can use the type()-function to get the type of a variable, resulting in type(matrNr) == int. This does exactly what you are trying to achieve.
Better solution
In Python you can define the types of variables a function accepts by adding : <type> after the argument. The better solution would thus be:
def DatenUebergeben(self, matrNr: int, vorname: str, nachname: str, gebDatum: list, telNr: str):
# do something
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Call function what checking file content, size, etc
Call function if file was changed by file size, if file size changed check file content, add changes to list or delete from list
Question how to use variable in other function correctly?
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size()
sleep(5.0)
Thank you in advance!
You need to assign the returned value of work_with_hosts_file() to a variable, and then pass that as an argument to compare_hosts_file_size().
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(file_size): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
size = work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size(size)
sleep(5.0)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i wanna to make a button to loop in all records and do a method that makes a list from ranges between tow fields and pop another record from the list and but the value in result field
i make it like in the code below and it work well just in the first record and the second record it working but without remove the record form the list and it's important for me to remove it like
then it stop working
class relate(models.Model):
_name = 'relate'
_rec_name = 'car'
#api.multi
#api.onchange('start', 'end', 'ignore')
def years_rang(self):
for rec in self.search([]):
if not rec.rang:
record = [int(x) for x in range(int(rec.start), int(rec.end) + 1)]
list = []
if rec.ignore:
try:
record.remove(int(self.ignore))
list= []
print(record)
except ValueError:
return {'warning': {'title': 'Warning!', 'message': "the Ignored year doesn't in range"}}
else:
for item in record:
range_id = self.env['yearrange'].create({'name': str(item)})
list.append(range_id.id)
rec.rang = [(4, x, None) for x in list]
else:
return
start = fields.Char(string="", required=False, )
end = fields.Char(string="", required=False, )
rang = fields.One2many(comodel_name="yearrange", inverse_name="product_id", store=True, string="Years" ,)
ignore = fields.Char(string="Ignore", required=False, )
class yearrange(models.Model):
_name = 'yearrange'
_rec_name = 'name'
name = fields.Char()
product_id = fields.Many2one(comodel_name="relate")
any kind of help will be appreciated
Adding print() in key parts helps tracing a lot.
If more is needed, import pdb; pdb.set_trace() would get you into a debugger REPL, provided that the process has a terminal (not running in a Lambda, etc).
The lack of explanation of what this code is doing and what kind of data it works on prevents an uninvolved observer from detecting any data-related bugs in it. What does self.search([]) even return?
Shadowing built-in identifiers like list is a bad idea, about as bad as having non-descriptive names like list.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How could I improve my code in python if I use a lot of lines like the following
post_title_tag = soup.find("h1", {"id": "post-title"})
if post_title_tag is None:
return
In this function
def get_post_data(url):
browser.get(url)
html_source = browser.page_source
soup = BeautifulSoup(html_source)
post_title_tag = soup.find("h1", {"id": "post-title"})
if post_title_tag is None:
return
description_tag = soup.find("p", class_="description")
if description_tag is None:
return
datetext_span = description_tag.find("span")
if datetext_span is None:
return
One option could be to wrap the parent function in a try/except block and use a function that throws an exception for you. Something like this:
class NoSuchTagException(Exception): pass
def get_tag(parent, name, *args, **kwargs):
child = parent.find(name, *args, **kwargs)
if child is None:
raise NoSuchTagException(name)
else:
return child
def get_post_data(url):
browser.get(url)
html_source = browser.page_source
soup = BeautifulSuop(html_source)
post_title_tag = get_tag(soup, 'h1', {'id': 'post-title'})
description_tag = get_tag(soup, 'p', class_='description')
datetext_span = get_tag(description_tag, 'span')
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to call/run a method only onetime I tried this but it didn't wotk:
class S ()
_int_(self)
self.xxx = True # i tried with and without
def Packet (event):
if (xxx == True):
self.f(event, xxx)
print xxx
else:
....
def f (event):
print "something"
Do_Somthing
xxx=False
the problem xxx is still true
Best regards
Amer
The whole class's syntax seems wrong to me. You can do something like this
class S:
def __init__(self): # Initializer function for instance members
self.flag = True
def myMethod(self): # Actual method to be called
if self.flag:
....
....
self.flag = False
Change xxx to self.xxx.
The xxx = False creates a new name binding instead of assigning to the field in your object.
Also, there are also some other syntax errors in your code. Is this the actual code you are running? The code you posted shouldn't run.
from itertools import count
class S ()
def __init__(self)
self.xxx = count()
def Packet(self, event):
if next(self.xxx) == 0:
self.f(event)
else:
....
def f(self, event):
print "something"
#Do_Something