How, if possible, would I be able to bring in a variable from an external function. Take this code
# HttpThing.py
import requests
def httpThing(someurl):
x = requests.get(someurl)
In another file I have
from httpThing.py import httpThing
httpThing(www.url.com)
print(x)
How would I be able to get the last print function to print the response to the query.
you return that value from the function like this:
# HttpThing.py
import requests
def httpThing(someurl):
x = requests.get(someurl)
return x
then use it like this:
from httpThing import httpThing
x = httpThing(www.url.com)
print(x)
NOTE: the variable that you return dosen't have to be same as the variable where you call that function for printing it. it could be named anything.
Related
I have following script that works well on it's own, but once I wrap it all into a function does not return data.
The command changes based on input data structure. This is an example of the command I want to feed into the exec():
cross_data=pd.crosstab(src_data['result'],[src_data['c1'],src_data['c2']],normalize='index')
This is my function I want to wrap the code in and call:
def calcct(file_path='src_data.csv', separator = ",", res_col = 'result'):
#define function
src_data = csv_import(file_path, separator) #import data
reorder_cols = reorder_columns(src_data, res_col) #work with data
head_list=list(reorder_cols.columns.values) #get dataframe headers
# create command based on headers and execute that. Should return dataframe called cross_data.
exec(crosstabcmd(head_list))
return cross_data
Results in:
NameError: name 'cross_data' is not defined
I cannot seem to find the correct syntax for calling exec inside a function.
I tried defining and passing the cross_data variable, but I just get an error it doesnt see pandas when I do that.
Or is there some better way? I need to compose the command of 2-x column names, count and names of columns are variable.
First up
You probably don't mean to be using exec - that's a pretty low-level functionality! There isn't really enough context to understand how to fix this yet. Could you write out (in your question) what the crosstabcmd function looks like?
The error
NameError: name 'cross_data' is not defined
is because you've never defined a variable called cross_data in the scope of function calcct, i.e. you have never done cross_data = "something".
I'll give it a go
Assuming you have something like
import pandas as pd
def crosstabcmd(head_list):
# ? I can only guess what your crosstabcmd does, this won't work though
return pd.crosstab(*head_list, normalize='index')
then the solution would look like:
def calcct(file_path = 'src_data.csv', separator = ",", res_col = 'result'):
src_data = csv_import(file_path, separator) #import data
reorder_cols = reorder_columns(src_data, res_col) #work with data
head_list=list(reorder_cols.columns.values) #get dataframe headers
cross_data = crosstabcmd(head_list)
return cross_data
In my case I had main script which called a second script. I needed to use the "c" variable within the second script. Therefore I used locals(),loc as arguments for exec().
loc = {}
a = 10
b = 5
def abc(a,b):
qwerty = "c = %d + %d"%(a,b)
exec(qwerty, locals(), loc)
c = loc['c']
d = c+2
print(d)
abc(a,b)
I have 4 python files, the first two is the function itself, the second is functions dictionary, and the third is kind of a 'definition' parser
function_1
def increment(obj):
return obj+1
#another function
function_2
def decrement(obj):
return obj-1
#another function
function_dictionary
import fucntion1
import function2
FUNC_DICT = {
'increment': function1.increment,
'decrement': function2.decrement,
#another function
}
definition_parser
from function_dictionary import FUNC_DICT
def get_definition():
result = {}
for key, value in FUNC_DICT.items():
#check if value is from function_1 or function_2
#result[key] = 'function_1' or 'function_2', depends on its origin
return result
is it possible to compare function import? I tried it with is_in_function_1 = value is in function_1, doesn't work.
if it is not, what are the way around without much repetition?
You can get the module of functions via the __module__ property.
from function_dictionary import FUNC_DICT
def get_definition():
result = {}
for key, value in FUNC_DICT.items():
result[key] = value.__module__
return result
The output would look like the following:
{
'increment': 'function_1',
'decrement': 'function_2'
}
You could use the inspect module like so:
import inspect
print(inspect.getmodule(SequenceMatcher))
for example, if I inspect SequenceMatcher, the output is:
<module 'difflib' from 'C:\ProgramData\Anaconda2\lib\difflib.py'>
So to compare the origin of two functions, you could simply do this:
if inspect.getmodule(increment) == inspect.getmodule(decrement):
do stuff
I have a very simple problem, when I run the following code:
from random import randint
def create_random():
x = random.randint(1,4)
return x
print(create_random)
The output comes to this:
< function create_random at 0x7f5994bd4f28 >
Note: every character between "0x7f" and "f28" are random each time the code is run.
My goal was to be able to call the function multiple times with x being assigned a new integer value between 1 and 3 with each invocation.
You aren't actually calling the function. To do this you need to do:
print(create_random())
Just now you're printing the reference to the function which isn't very helpful for you in this case.
You have to call the function, like:
print(create_random())
Also in the function, this line:
x = random.randint(1,4)
Should be just:
x = randint(1,4)
Since you did a from ... import ... statement.
your last line does not do anything, since you want it to print 'create_random' that is not a variable. if you want to call a function, it has to have (). So, you should call it and put it in the print function:
print(create_random())
so I know this has been asked in several forms before, but I cannot relate to any of those, either I have something different or I just don't understand them.
The problem is I have script A and script B, and in script A I calculate and have all the variables I want to use in script B.
Script A has various functions, let's say for now I just want to pass a simple number from a variable in script A to script B , let's call the variable value .
I used from script_A import value .
Now, I have value initialized in script_A with 0 right at the top to say so, but script_A processes value, and gets a result clearly different from 0, but when I debug, I am getting in script_B value == 0, and not value == calculated_value_that_should_be_there.
I did not know what to do so I tough about scope,so I put it in the return of a function, I tried making variable value a Global variable. Nothing seems to work in the way that I am not passing the calculated 'value' but I am passing to script_B that 0 initialization.
P.S last thing I tried and what I saw from this topic is to import script_A as it was said with no namespaces. This has worked. When I write script_A.value it is calculated_value_that_should_be_there. But, I do not know why anything else that I described did not work.
script_A
from definitions import *
variable_1 = 0
variable_2 = 0
variable_3 = 0
variable_4 = 0
total = 0
respected = 0
time_diff = {}
seconds_all_writes = "write"
class Detect():
def __init__(self, data_manager, component_name, bus_name_list=None):
def __Function_A(self):
"""
global time_diff
global seconds_all_writes
process
script_B:
from script_A import respected
from script_A import total
import script_A
print aln_mon_detector.total
print aln_mon_detector.respected
I also want a dictionary
table_content.append(script_A.time_diff[file[script_A.seconds_all_writes])
I get
KeyError: 'writes'
this sounds a bit confusing without an example, but, in principle, what you're trying to do should work. Have a look at a minimum example below.
ModuleA - defining the variable
# create the variable
someVariable = 1.
# apply modifications to the variable when called
def someFunc(var):
return var + 2
# ask for changes
someVariable = someFunc(someVariable)
ModuleB - using the variable
import moduleA
# retrieve variable
var = moduleA.someVariable
print(var) # returns 3
This probably has to do with immutability. Depends on what value is. If value is a list (that is, a mutable object) and you append to it, the change should be visible. However, if you write
from module import x
x = 5
you are not changing the actual value, so other references to x will still show the original object.
If you have script A like this:
# imports
value = 0
... # some calculations
Re-organize script A as:
# imports
def main():
value = 0
... # some calculations
return value
Now you can import script A in script B and run calculations inside script B:
import script_A
value = script_A.main()
That is how you should organize code pieces in Python.
I'm sure this is absurdly simple but I have been unable to get it working.
I want to return the value of x from within my function test in the module 'user_module' to my 'main_program'
file: user_module
def test ():
x =5
return x
file: main_program
import user_module
user_module.test()
print x
However the above code does not work :( I get the following error
NameError: name 'x' is not defined
In your module x is defined within the function test.
That means that it is only availavle inside the scope of that function.
Even if you would try to access x from within the module you would get a name error because x was not globally defined in that module.
This would not work:
file: user_module
def test ():
x =5
return x
print x
Produces a NameError.
(that does not mean the general solution is making everything globally available...)
To solve your problem you could create a variable named x.
You would have to change your code like this:
import user_module
x = user_module.test()
print x
Or instead of printing x you could just print the result of test().
print user_module.test()
This is because x is defined in a function, which means it is in the function's scope, not in the module's. But your function is returning it — which is good:). So use one of these solutions to get x:
1.
import user_module
print user_module.test()
2.
If you want to pass x from one module to another, then your user_module will look like this:
x = 5
and in the main script you do this:
import user_module
print user_module.x
3.
Or you can do this in your user_module:
def test():
x = 5
return x
x = test()
Now in your main script you do this:
import user_module
print user_module.x