Suggestions for improving this Python code [closed] - python

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')

Related

Create new class with init [closed]

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
I need to create new class by type function.
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': ForeignKeyRawIdWidget.__init__(
rel=rel,
admin_site=admin.site)}
)
But there is a problem. I need to change __init__ in new class, how to do it?
You probably want something like:
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
def __init__(self):
return ForeignKeyRawIdWidget.__init__(self, rel=rel, admin_site=admin.site)
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': __init__}
)

How to make a Class out of list [closed]

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
Hi I am new to Python and I am trying to make a class out of a list from a file and I am wondering if it is even possible or is it better to use dictionaries. My class looks like this:
class Program:
def __init__(self, name, start_time, end_time, channel):
And the list looks like it:
['Channel 1', '16.00-17.45 News', '17.45-17.50 Weather', '17.50-17.57 Friends', '17.57-18.00 Coming up', '18.00-18.15 MASH', '18.15-18.40 Thundercats]
Is there ant easy way to do it?
This is one of the approach:
data = ['Channel 1', '16.00-17.45 News', '17.45-17.50 Weather', '17.50-17.57 Friends', '17.57-18.00 Coming up', '18.00-18.15 MASH', '18.15-18.40 Thundercats']
class Program:
def __init__(self, start_time, end_time, name):
self.start_time = start_time
self.end_time = end_time
self.name = name
class Channel:
def __init__(self, channel_name, program_list):
self.channel_name = channel_name
self.program_list = program_list
plist = []
channel1 = Channel(data[0], plist)
for i in range(1, len(data)):
name = data[i][12:]
start_time = data[i][0:5]
end_time = data[i][7:12]
p = Program(start_time, end_time, name)
channel1.program_list.append(p)

Better way to use variables in this function? [closed]

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

can two different methods have different args in a class? [closed]

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 want to add the age for users in a different method but some users might not have an age argument
class User:
"""a class to save info about every user """
def __init__(self, user_name, num_id):
self.name = name
self.mun_id = num_id
def age(self, age):
self.age = age
user1 = User("martin", "1")
print (user1.name)
Yes you can set user age separately. Example below:
user1.age(20)
print (user1.age)
#20 will print
define age = None like below and this optional argument should be the last one:
def age(self, age = None):

How to call/run a method only one time in python [closed]

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

Categories

Resources