Within a class in Python:
I have this variable that I pass through a function called "changers"
energy_L_gainer = changers('cap_largeover,','sec_energy','-change')
When I call upon this variable from another function, how can I get it to pass back through the function again to refresh the data in the variable. I have searched everywhere and tried all that my small mind could muster, and I cannot get it to work. Any ideas? Thank you all so much.
Can you rerun the class somehow within the function to refresh the variables?
I called upon this variable within another function using:
self.energy_L_gainer
Here is the changers function for reference:
def changers(cap, sec, sort):
screen = requests.get(f'https://finviz.com/screener.ashx?v=111&f={cap}{sec},geo_usa&ft=4&o={sort}', headers = headers).text
tables = pd.read_html(screen)
tables = tables[-2]
tables.columns = tables.iloc[0]
tables = tables[1:]
return tables
Make it a property on your class
#property
def energy_L_gainer(self):
return changers('cap_largeover,','sec_energy','-change')
Now any reference to self.energy_L_gainer will use the result of that function
I'm not quite sure I'm following you, but you probably need to use self.energy_L_gainer = instead of energy_L_gainer =. In Python those two aren't the same like they can be in some other languages.
Related
I am trying to access data from an HTML form and use it in Flask. I was successfully able to get the data but I am not quite sure how to return it through function and use the returned variable inside FLask as a global variable.
#app.route('/form',methods=["POST"])
def search():
company=request.form.get("symbol"
return render_template('chart.html', Name=company)
I am only able to use the data of the company variable inside the function but I want to be able to use it outside the function. I have tried calling the function but it does not help.
If you return with render_template(), then the company variable will be available only inside the function and the html file.
For accessing outside function
Try making a class and then set the self.company in the method
Return company from the function and have a separate
rendering logic.
I come from a ruby background and I am noticing some differences to python... In ruby, when I need to create a helper I usually go for a module, something like the below:
module QueryHelper
def db_client
#db ||= DBClient.new
end
def query
db_client.select('whateverquery')
end
end
In python tho, I do something like the following:
db_client = DBClient()
def query():
return db_client.select('whateverquery')
My only worry with the above is that every time I call query() function it will try to instantiate DBClient() over and over... but based on reading and testing, that does not seem to occur due to some caching mechanism in python when I import a module...
The question is if the above in python is bad practice, if so, why and how can it be improved? perhaps lazy evaluating it? Or if you guys believe it's ok as is...
No. The query function will not be re-instantiated every time you call it. This is because you've already created an instance of DBClient outside of the query function. This means that your current code is fine as is.
If your intention was to create a new instance of DBClient every time query is called, then you should just move the declaration into the query function, like this:
def query():
db_client = DBClient()
return db_client.select( ... )
In short you would like to add a method to the DBClient object? Why not adding it dynamically?
# defining the method to add
def query(self, command):
return self.select(command)
# Actually adding it to the DBClient class
DBClient.query = query
# Instances now come with the newly added method
db_client = DBClient()
# Using the method
return_command_1 = db_client.query("my_command_1")
return_command_2 = db_client.query("my_command_2")
Credits to Igor Sobreira.
I currently have a class urldata.py, with a loop:
from Scanner.views import Processinitialscan
for element in elements:
dbInsert = PathsOfDomain(pathToScan=element.attrs["href"],FKtoTld=Processinitialscan.)
dbInsert.save()
I have a view.py with a variable EnteredDomainRowID, that I want to use in the class above:
def Processinitialscan(request):
EnteredDomainRowID = GetEnteredDomainObjects.pk
I've been trying:
FKtoTld=Processinitialscan.EnteredDomainRowID
in :
dbInsert = PathsOfDomain(pathToScan=element.attrs["href"],FKtoTld=Processinitialscan.)
but, this doesn't seem to work.
My question, how do I access the value from the variable EnteredDomainRowID from views.py within my class urldata.py for the variable dbInsert (as shown above) ?
Additionally, I cannot seem to be able to import views.py into a urldata.py , is this not possible?
Any help is really, really appreciated.
Thank you.
Unfortunately, that's not the way python works EnteredDomainRowID is not a property of your function object, but it is a local variable to the function.
You could pretty easily convert this to a class based view, which will allow you to easily access the classes attributes.
I've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.
This is my readRSS function (note that 'get' is a method of Kenneth Reitz's requests module):
def readRSS(name, loc):
linkList = []
linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title'))
linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link'))
for title, loc in zip(linkTitles, linkLocs):
linkList.append((title.text, loc.text))
return {name: linkList}
This is one of my MongoAlchemy classes:
class Feed(db.Document):
feedname = db.StringField(max_length=80)
location = db.StringField(max_length=240)
lastupdated = datetime.utcnow()
def __dict__(self):
return readRSS(self.feedname, self.location)
As you can see, I had to call the readRSS function within a function of the class, so I could pass self, because it's dependent on the fields feedname and location.
I want to know if there's a different way of doing this, so I can save the readRSS return value to a field in the Feed document. I've tried assigning the readRSS function's return value to a variable within the function __dict__ -- that didn't work either.
I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from).
Is there a way of doing what I intend to do or am I going about this all wrong?
I found out the answer. I needed to make use of a computed_field decorator, where the first argument was the structure of my return value and deps was a set which contained the fields that this field was dependent on. I then passed the dependent fields into a function's arguments and there you have it.
#fields.computed_field(db.KVField(db.StringField(), db.ListField(db.TupleField(db.StringField()))), deps=[feedname, location])
def getFeedContent(a=[feedname, location]):
return readRSS(a['feedname'], a['location'])
Thanks anyway, everyone.
Suppose I am building a composite set of types:
def subordinate_type(params):
#Dink with stuff
a = type(myname, (), dict_of_fields)
return a()
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_types)
#Now I want to edit some of the values in myawesomedynamictype's
#lots_of_types.
return myawesomedynamictype()
In this particular case, I want a reference to the "typeclass" myawesomedynamictype inserted into lots_of_types.
I've tried to iterate through lots_of_types and set it, supposing that the references were pointed at the same thing, but I found that the myawesomedynamictype got corrupted and lost its fields.
The problem I'm trying to solve is that I get values related to the type subordinate_type, and I need to generate a toplevel instantiation based on subordinate_type.
This is an ancient question, and because it's not clear what the code is trying to do (being a code gist rather than working code), it's a little hard to answer.
But it sounds like you want a reference to the dynamically created class "myawesomedynamictype" on the class itself. A copy of (I believe a copy of) the dictionary lots_of_types became the __dict__ of this new class when you called type() to construct it.
So, just set a new attribute on the class to have a value of the class you just constructed; Is that what you were after?
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_types)
myawesomedynamictype.myawesomedynamictype = myawesomedynamictype
return myawesomedynamictype()