accessing the "local" variable - python

def get(self):
if self.request.get('fmt')=='json':
KeyofQuestion = self.request.path[1:]
QuestionText = Question.get_by_key_name(KeyofQuestion).question
AnswersQuery = Question.get_by_key_name(KeyofQuestion).answers_collection
a=[]
Jsonobject = {'Question':QuestionText}
for each in AnswersQuery:
a = a.append(each.answer)
Hey, i am just confused that when I run the codes above, I got an error that says, Nonetype variable:a doesnt have method append, but I declared the a as a list before I called and they are inside the same function "get", so I assumed they are all treated as local variables. How come it cant map it? Thank you

You are assigning None to a. Change this:
a = a.append(each.answer)
to:
a.append(each.answer)

Related

How to print the variable inside the function

My code is below. trying to print the htmlStr inside the function. Is there any way
import urllib.request
import re
url = 'http://dummy.restapiexample.com/api/v1/employees'
def testhtml(self):
response = urllib.request.urlopen(url)
htmlStr = response.read().decode('ISO-8859-1')
with open("html.csv","a+") as file:
file.write(htmlStr)
pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
return pdata
print (htmlStr) I did outside the function thrown error
when I did print (htmlStr) got the error NameError: name 'htmlStr' is not defined
You're getting an error because you're trying to access a local variable outside of its domain.
Here's what this looks like in your code:
# 1. Begin creating your function
def testhtml(self):
# 2. This is a local environment.
# Any variables created here will not be accessible outside of the function
response = urllib.request.urlopen(url)
# 3. The local variable `htmlStr` is created.
htmlStr = response.read().decode('ISO-8859-1')
with open("html.csv","a+") as file:
# 4. Your local variable `htmlStr` is accessed.
file.write(htmlStr)
pdata = re.findall(r'"employee_name":"(\'?\w+)"', htmlStr)
return pdata
# 5. Your function is now complete. The local variable `htmlStr` is no longer accessible.
Does that make sense?
If you want to print your function (while debugging) you can place a print statement in the function. (Just make sure to eventually remove it to prevent disorganized console readouts.) If you need to access the variable outside of the function, consider including in the output.

How to set explicit variables in an URL - python

In the following code snippet at the bottom, how do I explicitly set {0} and {1} to variables like:
0=host-123
1=128.24.22.21
such that I can keep the URL with the variables and call those variables elsewhere without actually explicitly setting them as host-123 and 128.24.22.21 elsewhere ?
def getipam(host, neighboraddr, token):
"""Fetch IPAM data for host and neighbor ip"""
url = 'https://ipam.app.secretcdn.net/v1/hosts/{0}/bgp/neighbors/neighbor/{1}'.format(host, neighboraddr)
response = requests.get(url, headers={'x-api-rw': token})
results = response.json()
return results
0/1/integers are immutable in python. You cannot change the value. You might want to call it by some other name like x or y something and then you can assign it

Trouble sending boto3 filtered data to a list

I've generated a working boto3 instance filter using anaconda python 2.7. I need to assign the IP addresses and instance names to a list for further processing.
Code looks like this:
for instance in instances:
print(instance.id, instance.instance_type, instance.key_name, instance.private_ip_address, instance.public_dns_name ,instance.tags[0].get("Value"))
tagged = ec2.instances.filter(Filters=[{'Name': 'tag:My', 'Values': ['tag']}])
for instance in tagged:
print(name, instance.id, instance.private_ip_address)
object_list={}
object_list['requests']=[]
for instance in tagged:
tagged.collections.OrderedDict()
tagged['ip-address'] = instance.private_ip_address
tagged['machine'] = name
tagged['roles'] = ['tagged',instance.id,name]
object_list['requests'].append(tagged)
This is the error:
AttributeError: 'ec2.instancesCollection' object has no attribute 'collections'
Thoughts?
this doesn't exist but you have a cryptic error because you are reusing your tagged variable which is an instance of ec2.instancesCollection
tagged.collections.OrderedDict()
(and would do nothing anyway since it's not affected)
you (probably) want/wanted:
tagged = collections.OrderedDict()
but that doesn't make sense since you're already iterating on tagged.
You have to declare another variable
for instance in tagged:
t = collections.OrderedDict()
t['ip-address'] = instance.private_ip_address
t['machine'] = name
t['roles'] = ['tagged',instance.id,name]
object_list['requests'].append(t)

Global variable not recognized in functions

I know that this question looks exactly like so many other on here, because I just read them all and they all say to do what I already tried, and it hasn't worked (or I'm missing a subtle difference with my situation). Here is my situation:
I am writing a scraper using Scrapy and Python 2.7.11, and my code looks like this (this is a copy and paste with irrelevant lines omitted, but I can re-add them upon request):
class LbcSubtopicSpider(scrapy.Spider):
...omitted...
rawTranscripts = []
rawTranslations = []
def parse(self, response):
#global rawTranscripts, rawTranslations
rawTitles = []
rawVideos = []
for sel in response.xpath('//ul[1]'): #only scrape the first list
...omitted...
index = 0
for sub in sel.xpath('li/ul/li/a'): #scrape the sublist items
index += 1
if index%2!=0: #odd numbered entries are the transcripts
transcriptLink = sub.xpath('#href').extract()
#url = response.urljoin(transcriptLink[0])
#yield scrapy.Request(url, callback=self.parse_transcript)
else: #even numbered entries are the translations
translationLink = sub.xpath('#href').extract()
url = response.urljoin(translationLink[0])
yield scrapy.Request(url, callback=self.parse_translation)
print rawTitles
print rawVideos
print rawTranslations
def parse_translation(self, response):
global rawTranslations
for sel in response.xpath('//p[not(#class)]'):
rawTranslation = sel.xpath('text()').extract()
rawTranslations.append(rawTranslation)
This will return an error any time either "print rawTranslations" or "rawTranslations.append(rawTranslation)" is called because the global "rawTranslations" is not defined.
As I said before, I have looked into this pretty extensively and pretty much everyone on the internet says to just add a "global (name)" line to the beginning of any function you'd use/modify it in (although I'm not assigning to it ever, so I shouldn't even need this). I get the same result whether or not my global lines are commented out. This behavior seems to defy everything I've read about how globals work in Python, so I suspect this might be a Scrapy quirk related to how parse functions are called through scrapy.Request(....).
Apologies for posting what appears to be the same question you've seen so much yet again, but it seems to be a bit twisted this time around and hopefully someone can get to the bottom of it. Thanks.
In your case the variable you want to access is not global, it is in the scope of the class.
global_var = "global"
class Example:
class_var = "class"
def __init__(self):
self.instance_var = "instance"
def check(self):
print(instance_var) # error
print(self.instance_var) # works
print(class_var) # error
print(self.class_var) # works, lookup goes "up" to the class
print(global_var) # works
print(self.global_var) # works not
You only need the global keyword if you want to write to a global variable. Hint: Don't do that because global variables that are written to bring nothing but pain and despair. Only use global variables as (config) constants.
global_var = "global"
class Example:
def ex1(self):
global_var = "local" # creates a new local variable named "global_var"
def ex2(self):
global global_var
global_var = "local" # changes the global variable
Example().ex1()
print(global_var) # will still be "global"
Example().ex2()
print(global_var) # willnow be "local"
if you want to use variable in class, you can use self.xxx
class A:
... var = []
... def test(self):
... self.var.append(10)
... print self.var

Getting error message when trying to attach a class to an object

i have a little problem when i try to attach a class to an object in python. I have a textfile 'file', which is seperated into a list for each line. The program will read every line and print a name and a longname. Imagine that the textfile look like this:
"John '\n' John Travolta" (...)
Here's my bit of code:
class Name:
def __init__(self, name, longname):
self.name=name
self.longname=longname
def __str__(self):
s="Name:"+self.name
s+="\n Longname:"+self.longname
def func():
for line in file:
name=line[:1]
longname=line['\n':]
c=Name(name, longname)
c.func()
I get the error message that my 'name' and 'longname' is not defined but I did this with my function??? :(
It works if I put the function outside the class, like this:
def func():
for line in file:
name=line[:1]
longname=line['\n':]
c=Name(name, longname)
print c
Need help!
You need to assign something to name and longname before you can use them:
name = 'foo'
longname = 'foo bar'
c=Name(name, longname)
c.func()
but I did this with my function?
No.
Firstly, you didn't call your function yet. The function call is after the line that gives the error.
Secondly, the function has its own scope. The name there is different from the global name.
I don't think it makes any sense to move your func method inside the class definition. The code that you said works is a better way to do it.

Categories

Resources