问题
I have this folder hierarchy:
|---- saga
|---- core
|---- views.py
|---- study_time
|---- views.py
On my study_time/views.py
, I have this functions:
def study_time(request):
def tasks_subjects(week_day, key):
#Code here
return __tasks
def day_studies(week_day):
__tasks_subjects = tasks_subjects(week_day, 0)
#Code here
return __studies
return render(request, 'study_time.html', context)
On my core/views.py
, I need the day_studies() function, so I'm importing like this:
from saga.study_time.views import day_studies
def home(request):
day_progress = day_studies(datetime.date.today().isoweekday())
But I'm getting the error:
ImportError: cannot import name 'day_studies'
How can I make this importation? I don't want to reply all code.
回答1:
You've defined a nested function. That simply isn't visible outside the containing function; in fact, making it invisible from outside is pretty much the only good reason for defining nested functions in Python. Don't do that; move it outside the study_time
function.
(Also, don't use double-underscore prefixes like that. They don't make any sense outside a class; and even there you should rarely if ever use them.)
回答2:
The inner function is not accessible,because it is local code for that function only. It is not generic for all in the views.py . So make a distinction on this.
Go through this for better understanding!! https://realpython.com/blog/python/inner-functions-what-are-they-good-for/
Happy coding!!
来源:https://stackoverflow.com/questions/47676426/how-import-a-function-from-another-view-with-django