In Step 1 we used positional arguments.
lab_4_step_2_keyword_arguments.py
import boto3 def translate_text(text, source_language_code, target_language_code): client = boto3.client('translate') response = client.translate_text( Text=text, SourceLanguageCode=source_language_code, TargetLanguageCode=target_language_code ) print(response) def main(): translate_text('I am learning to code in AWS','en','fr') if __name__=="__main__": main()
In the next step, we are going to replace the positional arguments with keyword arguments.
A keyword argument is a name-value pair that is passed to the function. Here are some of the advantages:
**
Modify your function as follows:
import boto3 def translate_text(**kwargs): client = boto3.client('translate') response = client.translate_text(**kwargs) print(response) def main(): translate_text(Text='I am learning to code in AWS',SourceLanguageCode='en',TargetLanguageCode='fr') if __name__=="__main__": main()
To run the program, enter the following command in the terminal:
python lab_4_step_2_keyword_arguments.py.
python lab_4_step_2_keyword_arguments.py
**kwargs
Text=text
response = client.translate_text(**kwargs)
Text='I am learning to code in AWS'
In the last example, we defined keyword arguments using the syntax key=value. In the dictionaries part of the workshop we learned that dictionaries use a very similar format of "key":"value"
key=value
"key":"value"
AWS will often return information in the dictionary "key":"value" format. We can use these as our keyword values in our function easily.
Next, modify how we call the function. Change the syntax from key=value to "key":"value"
import boto3 def translate_text(**kwargs): client = boto3.client('translate') response = client.translate_text(**kwargs) print(response) ### Change below this line only ### kwargs={ "Text":"I am learning to code in AWS", "SourceLanguageCode":"en", "TargetLanguageCode":"fr" } def main(): translate_text(**kwargs) if __name__=="__main__": main()
kwargs
key:value
kwargs does not have to be used. You can define the name used.
Being able to pass a dictionary of key:value pairs rather than keyword pairs is useful because in AWS inputs to programs often use dictionaries.