Created
July 18, 2022 20:15
-
-
Save iuriguilherme/892b18614a92d78b0e37e8baf9ca4cf8 to your computer and use it in GitHub Desktop.
Colocar main.py e config.py no mesmo diretório
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Arquivo de configuração""" | |
attr: str = "Original" | |
def func(n: int) -> int: | |
"""Multiplica um número natural por 3""" | |
return n * 3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Altera um arquivo python que já foi importado e recarrega os atributos | |
AVISO: NÃO FAÇA ISSO EM CASA! | |
SE O TEU COMPUTADOR EXPLODIR PORQUE TU COPIOU E COLOU MEU CÓDIGO, | |
A CULPA É TUA! CONSIDERE-SE OFICIALMENTE AVISADO!!! | |
""" | |
from importlib import reload | |
## config.py | |
import config | |
print(config.attr) ## Original | |
print(type(config.attr)) ## <class 'str'> | |
print(config.func) ## <function func at 0x7f652a2ebd00> | |
print(type(config.func)) ## <class 'function'> | |
print(config.func.__doc__) ## Multiplica um número natural por 3 | |
print(config.func(2)) # 6 | |
with open('config.py', 'w') as arquivo: | |
arquivo.write(''' | |
"""Arquivo de alteração""" | |
attr: str = "Novo" | |
def func(n: int) -> int: | |
"""Multiplica um número natural por 666""" | |
return n * 666 | |
''') | |
## importlib.reload só funciona do jeito certo (tm) com modulos que foram | |
## importados usando "import config". se tu usar a sintaxe | |
## "from abc import config", gambiarras adicionais vão ter que ser feitas | |
## porque os submódulos de pacotes não são recarregados. a referência na | |
## memória vai ser a mesma, e isto vai ter efeitos colaterais que podem ou | |
## não ser desejáveis. mas o comportamento não é confiável porque pode | |
## mudar em diferentes versões do python. | |
## então o jeito suficientemente seguro é fazer "import config" e depois | |
## reload(config). | |
reload(config) | |
print(config.attr) ## "Novo" | |
print(type(config.attr)) ## <class 'str'> | |
print(config.func) ## <function func at 0x7f652a2ebd90> | |
print(type(config.func)) ## <class 'function'> | |
print(config.func.__doc__) ## Multiplica um número natural por 666 | |
print(config.func(2)) ## 1332 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment