Python variável atribuída por um módulo externo é acessível para imprimir mas não para atribuição no módulo de destino

StackOverflow https://stackoverflow.com/questions/605399

  •  03-07-2019
  •  | 
  •  

Pergunta

Eu tenho dois arquivos, um é no webroot, e outra é uma inicialização localizada uma pasta acima da raiz web (esta é a programação CGI, por sinal).

O arquivo de índice nas importações de raiz web do bootstrap e atribui uma variável a ele, em seguida, chama uma função para inicializar a aplicação. Tudo até aqui funciona como esperado.

Agora, no arquivo de inicialização posso imprimir a variável, mas quando eu tentar atribuir um valor à variável um erro é lançado. Se você tirar a instrução de atribuição sem erros são jogados.

Estou muito curioso sobre como o escopo funciona nesta situação. Posso imprimir a variável, mas não posso Assign a ele. Esta é em Python 3.

index.py

# Import modules
import sys
import cgitb;

# Enable error reporting
cgitb.enable()
#cgitb.enable(display=0, logdir="/tmp")

# Add the application root to the include path
sys.path.append('path')

# Include the bootstrap
import bootstrap

bootstrap.VAR = 'testVar'

bootstrap.initialize()

bootstrap.py

def initialize():
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

Graças.

Edit: A mensagem de erro

UnboundLocalError: local variable 'VAR' referenced before assignment 
      args = ("local variable 'VAR' referenced before assignment",) 
      with_traceback = <built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0>
Foi útil?

Solução

tente o seguinte:


def initialize():
    global VAR
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

Sem 'VAR global' python quiser usar VAR variável local e dar-lhe "UnboundLocalError: variável 'VAR' local referenciado antes atribuição"

Outras dicas

Do not declará-la global, passá-lo em vez e devolvê-lo se você precisa ter um novo valor, como este:

def initialize(a):
    print('Content-type: text/html\n\n')
    print a
    return 'h'

----

import bootstrap
b = bootstrap.initialize('testVar')
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top