使用iPython Notebook时NameError(来自函数)

时间:2016-03-21 21:52:22

标签: python function ipython nameerror

这是一个非常简单的错误。相同的代码直接在笔记本单元格中运行(正常工作)VS在函数中定义,然后在单元格中调用(不起作用)

如果我在笔记本中运行此代码,它可以正常工作:

import datetime
now = datetime.datetime.now()

#other date stuff for later
today = datetime.datetime(now.year,now.month,now.day)
yesterday = datetime.date.today() - datetime.timedelta(1)
thisyear = datetime.datetime(now.year,1,1)
daynum = (today-thisyear).days

#print report date info
print('Report for the date: %s  (day #%d)'%(yesterday,daynum))
print('Produced at: [%s]'%now)

但是,如果我在另一个文件(同一文件夹)中使用该代码定义一个函数,则在名为defs.py的文件中

def currentdates():
    import datetime
    now = datetime.datetime.now()

    #other date stuff for later
    today = datetime.datetime(now.year,now.month,now.day)
    yesterday = datetime.date.today() - datetime.timedelta(1)
    thisyear = datetime.datetime(now.year,1,1)
    daynum = (today-thisyear).days

    return(now,today,yesterday,thisyear,daynum)

然后尝试在笔记本中运行它,它不起作用:

#setup dates
from defs import currentdates
from obspy import UTCDateTime

[now,today,yesterday,thisyear,daynum] = currentdates()

#print report date info
print('Report for the date: %s  (day #%d)'%(yesterday,daynum))
print('Produced at: [%s]'%now)

这是我得到的错误:

NameError                                 Traceback (most recent call last)
<ipython-input-15-d85dba8d0bba> in <module>()
      5 from obspy import UTCDateTime
      6 
----> 7 [now,today,yesterday,thisyear,daynum] = currentdates()
      8 
      9 #print report date info

/home/morgan/SPYDER/defs.py in currentdates()
     57     daynum = (today-thisyear).days
     58 
---> 59     return(now,today,yesterday,thisyear,daynum)
     60 
     61 print('..imported: currentdates() - outputs: [now,today,yesterday,thisyear,daynum]')

NameError: global name 'year' is not defined

我已经查看了所有可以提出的问题,但就我所知,它们都有更复杂的问题。

我见过的其他非常相似的问题,但未能回答我的问题(它们通常似乎适用于'循环引用')

Botch-job解决方案

如果我在调用函数之前定义:“year = 2016”,它可以正常工作。也许ipython笔记本无法与计算机上的日历/时钟通信?它应该没有,因为功能肯定这样做?这听起来更像是一个错误而不是代码问题,可能吗?

0 个答案:

没有答案