Issue
In the below script I would like to use the name_type
global variable in the decorator
while calling the get_names
functions. Please don't worry about the program logic.
name_type=None
def main():
global name_type
name_type="FEMALE"
get_names()
def superNameDecorator(value):
def nameDecorator(func):
if value in ["MALE"]:
def wrapper1(*args,**kwargs):
original_result=func(*args,**kwargs)
modified_result= "<MALE>"+original_result + "<\MALE>"
return modified_result
return wrapper1
elif value in ["FEMALE"]:
def wrapper2(*args,**kwargs):
original_result=func(*args,**kwargs)
modified_result= "<FEMALE>"+original_result + "<\FEMALE>"
return modified_result
return wrapper2
return nameDecorator
@superNameDecorator(name_type)
def get_names():
name='AMY'
return name
if __name__ == "__main__":
main()
This works fine when I pass direct string either "MALE"/"FEMALE" but throws below error when passing name_type
What am I missing here?
Traceback (most recent call last):
File "GlobalTesting.py", line 29, in <module>
main()
File "GlobalTesting.py", line 5, in main
get_names()
TypeError: 'NoneType' object is not callable
Solution
When get_names
is defined, name_type
is None
, because main
hasn't been called yet. Neither of the if/elif
clauses get run, so nameDecorator
returns None
, which gets bound to the identifier get_names
. One solution would be to remove main
and just make it a __name__
check near the top of the file.
import os
import re
import sys
name_type=None
if __name == '__main__': # If this doesn't happen, this error will still occur.
name_type="FEMALE"
def superNameDecorator(value):
def nameDecorator(func):
if value in ["MALE"]:
def wrapper1(*args,**kwargs):
original_result=func(*args,**kwargs)
modified_result= "<MALE>"+original_result + "<\MALE>"
return modified_result
return wrapper1
elif value in ["FEMALE"]:
def wrapper2(*args,**kwargs):
original_result=func(*args,**kwargs)
modified_result= "<FEMALE>"+original_result + "<\FEMALE>"
return modified_result
return wrapper2
return nameDecorator
@superNameDecorator(name_type)
def get_names():
name='AMY'
return name
if __name == '__main__':
get_names()
A more sensible solution would be to rewrite your nameDecorator
to handle any name_type
, and the lack of a name_type
, in some way that makes sense to you.
Answered By - Patrick Haugh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.