Get variable from a parent function - python

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

Related

How to get the output of an Object function as Variable

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

How to return a value from one python script to another?

file1.py
from processing file import sendfunction
class ban():
def returnhello():
x = "hello"
return x #gives reply a value of "hello replied" in processingfile
print(sendfunction.reply()) #this should fetch the value of reply from processingfile,right?
processingfile.py
from file1 import ban
class sendfunction():
def reply():
reply = (ban.returnhello() + " replied")
return reply
I can't really seem to get any results, any help would be appreciated.
You need to create object of class ban before calling his member function as follows
from file1 import ban
class sendfunction():
def reply(self): # Member methods must have `self` as first argument
b = ban() # <------- here creation of object
reply = (b.returnhello() + " replied")
return reply
OR, you make returnhello method as static method. Then you don't need to create an object of class beforehand to use.
class ban():
#staticmethod # <---- this is how you make static method
def returnhello(): # Static methods don't require `self` as first arugment
x = "hello"
return x #gives reply a value of "hello replied" in processingfile
BTW: Good programming practice is that, you always start you class name with Capital Letter.
And function and variable names should be lowercase with underscores, so returnhello() should be return_hello(). As mentioned here.
Lets suppose we have two file A.py and B.py
A.py
a = 3
print('saying hi in A')
B.py
from A import a
print('The value of a is %s in B' % str(a))
On executing B.py you get the following output:
└> python B.py
saying hi in A
The value of a is 3 in B

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.

Pyparsing SetParseAction trouble

I am a new-bee to pyparsing I am trying to experiment with setParseAction but it is not being called sometimes.
Here is the code
def fun():
comdty_tok = StringStart() + Word(alphas) + StringEnd()
comdty_tok.setParseAction(call_back)
comdty_tok.leaveWhitespace()
return comdty_tok
def call_back(p):
print 'Calling ....'
print p
class ComdtyTok(Token):
comdty_tok = StringStart() + Word(alphas) + StringEnd()
comdty_tok.setParseAction(call_back)
comdty_tok.leaveWhitespace()
parseImpl = comdty_tok.parseImpl
class SymParser(object):
tok = ComdtyTok()
#staticmethod
def parse(symbol):
p = SymParser.tok.parseString(symbol)
print p
print "Second"
x = fun()
x.parseString(symbol)
return p
SymParser.parse('ABCD')
I dont understand why the setParseAction is not called for the first time.
I just played with pyparsing for the first time, so ...
In initializing the class variable comdty_tok you never actually call parseString(), therefore the callback associated with the parse object is never called.
All I can say is that I did not really intend for classes like Token to be extended in the manner that you have done. I suspect that in your delegation to the contained cmdty_tok attribute that you have omitted exposing some other attribute, such as parseAction, which would normally be referenced at parse time by parseImpl. On the other hand, your implementation of fun() is very consistent with other helpers and closures I have used and seen used, and not surprisingly, this approach works.
What are you trying to accomplish with ComdtyTok?

Categories