为什么这段代码报错“IndentationError: unexpected unindent”?

1 投票
6 回答
4964 浏览
提问于 2025-04-16 20:54

下面的代码让我非常烦恼。我在StackOverflow和谷歌上查了很多,但还是没找到解决办法。其实我对Python编程还算不错,但直到现在,我还没有遇到过无法解决的错误。这段代码让我遇到了IndentationError: unexpected unindent,这很奇怪,因为通常的错误是“unexpected indent”,也就是缩进的问题。很多人都说这是因为空格不对,所以我仔细检查了整个代码,结果还是同样的错误。我明明正确地用了四个空格,但还是没解决问题……求助!

from bottle import Bottle, run, route, static_file, debug
from mako.template import Template as temp
from mako.lookup import TemplateLookup

lookup = TemplateLookup(directories=[base+'/templates'])
application = Bottle()

if __name__ == '__main__':
    @route('/')
else:
    @application.route('/')
def index():
    index_temp = lookup.get_template('index.html')
    return index_temp.render(site=site, corperate=corperate, copyright=copyright)

6 个回答

2

你尝试的做法不符合 def语句的语法规则。你可以试试这样做:

def index():
    index_temp = lookup.get_template('index.html')
    return index_temp.render(site=site, corperate=corperate, copyright=copyright)

if __name__ == '__main__':
    index = route('/')(index)
else:
    index = application.route('/')(index)
3

还有一种可能的解决方案,跟你说的很接近:

def decorate(func):
    if __name__ == '__main__':
       @route('/')
       def f():
          func()
    else:
       @application.route('/')
       def f():
          func()

    return f

@decorate
def index():
    index_temp = lookup.get_template('index.html')
    return index_temp.render(site=site, corperate=corperate, copyright=copyright)
9

我觉得你的想法是根据模块是直接运行还是被导入,给函数应用不同的装饰器。可惜的是,你现在的做法行不通,因为装饰器的调用需要紧接着函数后面。不过,你可以这样做:

if __name__ != '__main__':
    route = application.route

@route('/')
def index():
    index_temp = lookup.get_template('index.html')
    return index_temp.render(site=site, corperate=corperate, copyright=copyright)

或者,假设你在某个地方导入了 application,你可以直接用 from application import route,这样就不需要任何 if 语句了。

撰写回答