def lambda_handler(event, context): return { "statusCode": 200, "body": json.dumps({ "message": my_module.my_function() }), }
def increment(self, **kwargs): # input_model_name1 matches the name of a JSON file in the input schemas directory if "input_model_name1" in kwargs.keys(): # example_input1 and example_input2 refer to fields in the input schema self.input_data1 = kwargs["input_model_name1"]["example_input1"][ "data"] self.input_data2 = kwargs["input_model_name1"]["example_input2"][ "data"] # input_model_name2 matches the name of a JSON file in the input schemas directory if "input_model_name2" in kwargs.keys(): # example_input3 refers to a field in the input schema self.input_data3 = kwargs["input_model_name2"]["example_input3"][ "data"] # calculate the model's outputs output1, output2 = my_function(self.input_data1, self.input_data2, self.input_data3) # template_output_schema matches the name of the JSON file in the output schemas directory # example_output1 and example_output2 refer to fields in the output schema # example_output1 is returned by my_function() in the county granularity # example_output2 is returned by my_function() in the latlon granularity # before it is published, the data will automatically be translated to the granularities specified in template_output_schema return { "template_output_schema": { "example_output1": { "data": output1, "granularity": "county" }, "example_output2": { "data": output2, "granularity": "latlon" }, } }
import my_module # Uppgift 1 (givet) y = 222 x = 111 x_list = [111, 222, 333, 444] print("Outside module: x=" + str(x) + " and x_list=" + str(x_list) + " and y=" + str(y)) my_module.scope_testing_function(x, x_list) print("Outside module: x=" + str(x) + " and x_list=" + str(x_list) + " and y=" + str(y)) # Uppgift 2 print(my_module.my_function(2)) print(my_module.my_function(5)) # Uppgift 3 (att skrivas) print(my_module.roll_dice(5)) # Uppgift 4 (att skrivas) print(my_module.my_sort_list([3, 7, 5, 2, 1])) print(my_module.my_sort_list([5, 2, 1, 11, 10])) print(my_module.my_sort_list([1, 2, 3])) # Uppgift 5 (att skrivas) print(my_module.bandit_language("hej jag heter mikaela")) print(my_module.bandit_language("vad heter du?")) # Uppgift 6 (givet)
#!/usr/bin/env python import logging import logging.config import yaml import my_module with open('./logging_conf.yaml') as logging_config_filehandle: logging_config_dict = yaml.load(logging_config_filehandle) logging.config.dictConfig(logging_config_dict) logging.basicConfig() # logging.basicConfig() _or_ adding a handler is required to avoid the following error: # No handlers could be found for logger "root" logger = logging.getLogger() logger.critical('Log message at CRITICAL') logger.error('Log message at ERROR') logger.warning('Log message at WARNING') logger.info('Log message at INFO') # calls my_function that is contained within my_module my_module.my_function()
import my_module # Uppgift 1 (givet) y = 222 x = 111 x_list = [111, 222, 333, 444] print("Outside module: x=" + str(x) + " and x_list=" + str(x_list) + " and y=" + str(y)) my_module.scope_testing_function(x, x_list) print("Outside module: x=" + str(x) + " and x_list=" + str(x_list) + " and y=" + str(y)) # Uppgift 2 (att skrivas) print(my_module.getLine(50)) print("my_function retunerar: ", my_module.my_function(10)) print(my_module.getLine(50)) # Uppgift 3 (att skrivas) diceSum = my_module.roll_dice(10) print("Summan av slagen", diceSum) print(my_module.getLine(50)) # Uppgift 4 (att skrivas) listToSort = [1, 6, 3, 7, 8, 3, 2, 7, 4, 8, 1, 8, 4, 1, 9, 4, 2] my_module.my_sort_list(listToSort) print("Sorterad lista: ", listToSort) print(my_module.getLine(50)) # Uppgift 5 (att skrivas) print( "Konstig mening: ",
from my_module import my_function answer = my_function(29, 13) print('The answer is {}'.format(answer))
def test2(self): self.assertAlmostEqual(my_module.my_function(0), 0, "Verkar vara en bugg i my_function...") self.assertAlmostEqual(my_module.my_function(math.pi / 2), 1 + math.pi * math.pi / 4, "Verkar vara en bugg i my_function...")
def test_my_function_raises_exception(): with pytest.raises(TypeError): my_function(1, '3')
def test_for_equivalence(): result = my_function(2) assert result == True
def test_for_big_numbers(): result = my_function(3) assert result == True
def test_my_module(): result = my_function(1) assert result == False
def test_my_function_raises_exception(): with pytest.raises(TypeError): my_function(1, '3')
def test_my_function(): assert my_function(1, 3) == 4
import my_module print("This is My aap") print(my_module.my_var) print(my_module.my_function())
import my_module # provide a tutorial for understanding how a logger can be used to enable # logging in an imported module # to test - simply change the level set on the root logger # example # logger.setLevel(logging.DEBUG) # becomes # logger.setLevel(logging.WARNING) # # # create a root logger - creating a logger by itself would fail - there is no handler for the logger yet logger = logging.getLogger() # sets the log level for this module AND all imported modules logger.setLevel(logging.DEBUG) # create a StreamHandler - this will output to console console_handler = logging.StreamHandler() # apply the console_handler to the root logger we just created - without this there is no output logger.addHandler(console_handler) module_name = __name__ logging.critical('Log message at CRITICAL from {}'.format(module_name)) logging.error('Log message at ERROR from {}'.format(module_name)) logging.warning('Log message at WARNING from {}'.format(module_name)) logging.info('Log message at INFO from {}'.format(module_name)) logging.debug('Log message at DEBUG from {}'.format(module_name)) # calls my_function that is contained within my_module my_module.my_function()
def test_for_type(): try: result = my_function("abc") assert False except TypeError: assert True
def test_my_function(): assert my_function(1, 3) == 4
def test_for_small_numbers(): result = my_function(1) assert result == False
def test_my_function(): assert my_function("Jerome") == "Hello Jerome"
# MODULE RANDOM import random random.randint(0,100) # gera numero aleatorio entre 0 e 100 random.choice(x) # escolhe um item desse x (pode ser um string, p. ex.) random.sample(x, 5) # pega 5 do item x # MODULE COLLECTIONS from collections import namedtuple # importa a collecao namedtuple, que une vantagens de tuple (ser immutable) e de dict (nomear valores) from collections import orderedDict # importa orderedDict. Sao dicionarios com elementos numerados. # MODULES e PACKAGES # um module e' um arquivo com extensao .py import my_module res = my_module.my_function(3,4) # agrupar modules em pastas forma pacotes # navegandos em pacotes dentro de pacotes from my_package.a_module import my_function # ou seja, a pasta(pacote) my_package tem um arquivo(module) com a funcao. # os pontos serao usados tantas vezes quantas houverem pastas dentro de pastas # mas cuidado!!! para uma pasta virar o pacote 'e preciso criar um arquivo inicializavel dentro dela. ############################## #### AULA 8 : Exceptions #### ############################## # Exceptions é quando algo da errado no codigo: (i) pode ser uma falha do programador; # (ii) ou um erro no ambiente, como uma limitação no processamento.