How to get the output of an Object function as Variable - python

I am new to this and trying pass the output of this function as a string to the tweepy update method ( To post as a statue )
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
hello()
The Issue here is Tweepy's " api.update_status ( status ) " would only accept a string or a variable encasing a string. Using a Function call prints out errors.
How Do I go about this simple process?
I have tried to pass the function output as a variable
test = hello()
but this prints out errors to twitter.
...
api.update_status (test)

Your function return a None object, you function should return a string like
#furas mentioned above.
try this:
def hello():
name = input("Enter your name: ")
if name:
return "Hello " + name
else:
return "Hello World"
hello()
and you still pass a function call to the api
api.update_status(hello())

Related

How to call python api method inside another api in same class?

I have the following api method
#app.route('/api/v1/lessons', methods=['GET'])
def api_lessons():
if 'courseId' in request.args:
courseId = request.args['courseId']
else:
return "Error: No course id provided. Please specify an course id."
onto = get_ontology("ontology.owl")
onto.load()
result = onto[courseId].contains
result2 = []
for i in result:
temp = "{ id : " + str(i.Identifier) + ", name : " + str(i.Name) + "}"
print(temp)
result2.append(temp)
return json.dumps(result2)
And I need to add a new method to call this api internally with same args
#app.route('/api/v1/learningPath', methods=['GET'])
def api_learningPath():
lessons = api_lessons
return json.dumps(result2)
How to do that ?
You need to call the function instead of calling an internal API. Your api_lessons() will return a JSON string and you will need to parse it back to JSON in order to use it. Your function would be like this.
#app.route('/api/v1/learningPath', methods=['GET'])
def api_learningPath():
lessons = json.loads(api_lessons())
return json.dumps(result2)

Get variable from a parent function

I have a function that produces another function.
def make_func(greeting):
def func(name):
return greeting + " " + name
return func
>>> say_hello = make_func("Hello")
>>> say_hello("there")
"Hello there"
Elsewhere in the script, I have access to say_hello, but I have no idea what the greeting in that function actually is. I'd like to find out.
name, of course, isn't possible to get because it's specified when the function is called. But greeting is static, because it's defined outside of the function.
Is there some attribute of say_hello I can examine to get the original "Hello"?
You can find a good explanation of how inner functions are compiled in python here
Then the easiest way to get the variable is say_hello.__closure__[0].cell_contents
You can just store the attribute greeting in func:
def make_func(greeting):
def func(name):
return func.greeting + " " + name
func.greeting = greeting
return func
say_hello = make_func("Hello")
print(say_hello.greeting) # Hello
say_hello.greeting = 'Bye'
print(say_hello('there')) # Bye there

How to check arguments passed to the function call are empty?

I want the function to simply check if an argument is passed or not. If not, print something, else say some hello and that argument.
Here is sample of my code:
def say_name(name):
if name is None:
print("Hello there")
else:
print("Hello, "+ name + "!")
run code:
class Test(unittest.TestCase):
def test_should_say_hello(self):
self.assertEqual(say_name("Michael"), "Hello, Michael!")
I have tried using None, Kwargs and still not working. How can I check whether argument is passed to the function?
To make a parameter optional assign it a default value:
def say_name(name=None):
if name is None:
print("Hello there")
else:
print("Hello, "+ name + "!")
Addendum: As Barmar pointed out in the comments to your question, your function needs to return a string to make your check work.
def say_name(name=None):
if name is None:
return "Hello there"
else:
return "Hello, "+ name + "!"
To check whether "any" of the argument is passed with the function call
In general, in order to check whether any argument is passed or not, you may create your function using *args (for non-keyworded variable length argument list) and **kwargs (for keyworded variable length argument list). For example:
def check_argument(*args, **kwargs):
if args or kwargs: # check if any among the `args` or `kwargs` is present
return "Argument Passed!"
else:
return "Argument Not passed!"
Sample Run:
# For "non-keyworded" argument
>>> check_argument('something')
'Argument Passed!'
# For "keyworded" argument
>>> check_argument(some_param='some_value')
'Argument Passed!'
# For no argumenet
>>> check_argument()
'Argument Not passed!'
To check if any "specific" argument is passed with the function call
For your scenario, since you only care about one specific parameter name and perform operation based on the value passed, you may assign a default value to it's function definition as:
# v Default value as `None`
def say_name(name=None):
if name is None:
return "Hello, there!"
else:
return "Hello, "+ name + "!"
Above function could be simplified as:
# v setting default name as "there"
def say_name(name="there"):
return "Hello, {}!".format(name)
# Or you may also check it within the format as
def say_name(name=None):
return "Hello, {}!".format(name or "there")
Sample Run:
>>> say_name()
Hello, there!
>>> say_name('StackOverflow')
Hello, StackOverflow!
def say_hello(*name):
if name:
return "Hello, "+name[0]+"!"
else:
return "Hello there!"
This should work

How to change function name dynamically in python

I want to change the function name according to result obtained from another function but the function definition remains same How can i do this i tried the following example but it didn't work
def f(text):
def x(text):
return text+"example"
name=x(text)
def name(y):
return y
return name
p=f("hi ")
print p("hello")
print p.__name__
OUTPUT
hello
name
But i want the function name p.__name__ as "hi example" not name
You can simply assign to __name__:
def f(text):
def r(y):
return y
r.__name__ = text + "example"
return r
p = f("hi ")
print (p("hello")) # Outputs "hello"
print (p.__name__) # Outputs "hi example"
Note that a function name does not have any influence on the function's behavior though, and does not have any meaning except as a part of the string representation or a debugging aid.

How to get just the return value from a function in Python?

I'm trying to learn programming through Python and I like to know if it's possible to get just the return value of a function and not its other parts. Here's the code:
Let's say, this is the main function:
variable_a = 5
while variable_a > 0 :
input_user = raw_input(": ")
if input_user == "A":
deduct(variable_a)
variable_a = deduct(variable_a)
else:
exit(0)
Then this is the deduct function:
def deduct(x):
print "Hello world!"
x = x - 1
return x
What happens is that, it does the calculation and deduct until variable_a reaches 0. However, "Hello world!" gets printed twice, I think because of variable_a = deduct(variable_a) (correct me if I'm wrong). So I was thinking, can I just capture the return value of deduct() and not capture the rest? So that in this instance, after going through deduct(), variable_a would just have a plain value of 2 (without the "Hello world!").
Am I missing things? :?
Editor's note: I remove the blank lines, so it can be pasted to REPL.
The printing of "Hello world" is what's known as a side effect - something produced by the function which is not reflected in the return value. What you're asking for is how to call the function twice, once to produce the side effect and once to capture the function return value.
In fact you don't have to call it twice at all - once is enough to produce both results. Simply capture the return value on the one and only call:
if input_user == "A":
variable_a = deduct(variable_a)
else:
If you don't want your function to print output, the correct solution is to not use print in it. :P
The first time you call deduct, it doesn't do anything except print that message, so you could probably just remove that line and be fine.
However, there is a slightly messy way to suppress print statements. You can temporarily replace your program's output file with a placeholder that does nothing.
import sys
class FakeOutput(object):
def write(self, data):
pass
old_out = sys.stdout
sys.stdout = FakeFile()
print "Hello World!" # does nothing
sys.stdout = old_out
print "Hello Again!" # works normally
You could even make a context manager to make this more convenient.
import sys
class FakeOutput(object):
def __enter__(self):
self.out_stdout = sys.stdout
sys.stdout = self
return self
def __exit__(self, *a):
sys.stdout = self.out_stdout
def write(self, data):
pass
print "Hello World!" # works
with FakeOutput():
print "Hello Again!" # doesn't do anything
print "Hello Finally!" # works

Categories