reloaded modules python что значит
Spyder 2.3.4: I keep getting a «Reloaded modules:» warning #2325
Comments
gsmafra commented Apr 14, 2015
Since I updated Spyder I am getting these messages everytime I try to compile a script with an import a second time.
For example, when running 2x a script that simply imports theano I get this message:
Reloaded modules: theano.scalar, theano.gof.callcache, theano.gof.optdb, theano.scan_module.scan, theano.tensor.extra_ops, theano.tensor.io, theano.tensor.shared_randomstreams, theano.tensor.opt, theano.tensor.nnet.Conv3D, theano.compile.monitormode, theano.tensor.blas, theano.tensor.type, cutils_ext, theano.gradient, theano.compile.profilemode, theano.gof.compiledir, theano.gof.type, theano.tests.main, theano.misc.cpucount, theano.scan_module.scan_op, theano.gof.null_type, theano.compile, theano.tensor.utils, theano.tensor.blas_scipy, theano.misc.ordered_set, theano.gof.opt, theano.tests, theano.tensor.nlinalg, lazylinker_ext.lazylinker_ext, theano.tensor, theano.compile.builders, theano.compile.debugmode, theano.tensor.nnet, theano.compile.io, theano.gof.utils, theano.gof.destroyhandler, theano.tensor.nnet.ConvTransp3D, theano.scan_module.scan_opt, theano.misc, theano.compile.function_module, theano.gof.graph, theano.tensor.subtensor, theano.tensor.blas_c, theano.compat.python2x, theano.gof.cutils, theano.misc.windows, theano.tensor.nnet.conv, theano.scan_module.scan_utils, theano.compat.six, theano.tensor.basic, theano.configparser, theano.gof, theano.gof.fg, theano.configdefaults, theano.tensor.sharedvar, theano.gof.toolbox, theano.scan_module.scan_views, theano.tensor.blas_headers, theano.printing, theano.tensor.elemwise_cgen, theano.gof.link, theano, theano.scalar.sharedvar, theano.gof.vm, lazylinker_ext, theano.compile.ops, theano.gof.unify, theano.tensor.elemwise, theano.tensor.nnet.nnet, theano.compile.function, theano.tensor.type_other, theano.gof.cc, theano.tensor.sort, theano.version, theano.scalar.basic, theano.tensor.nnet.ConvGrad3D, theano.tests.unittest_tools, theano.tensor.xlogx, theano.tensor.var, cutils_ext.cutils_ext, theano.gof.compilelock, theano.compile.mode, theano.compile.sharedvalue, theano.misc.safe_asarray, theano.compile.pfunc, theano.tensor.nnet.sigm, theano.gof.lazylinker_c, theano.gof.sched, theano.misc.strutil, theano.scalar.basic_scipy, theano.gof.cmodule, theano.compat, theano.gof.op, theano.updates, theano.tensor.opt_uncanonicalize, theano.scan_module, theano.tensor.raw_random, theano.compile.profiling
That only happens when using Spyder’s runfile. I already tried execfile() and python xxx.py and I get no warnings
So, anyone knows how to suppress it?
Running on:
Python 2.7.8
Anaconda 2.1.0 (64-bit)
IPython 2.2.0
Windows 7
The text was updated successfully, but these errors were encountered:
Reloaded modules python что значит
How to avoid reloading modules in python
I am getting the warning: Chromosome_length is actually a function that I am calling in another *.py file via the following:
1) Why does a reloaded module happen?
2) What are the problems/issues it can cause?
3) How to avoid this happening?
P.S. I know how to deactivate the warning message, but I also want to understand why this is happening and how I should avoid it.
(May-04-2018, 08:26 PM) nilamo Wrote: Unless you’re doing something wacky with the importlib module, you can’t reload modules.
What’s the whole warning/error message? Is there a traceback?
It’s actually the warning that I mentioned only:
I can deactivate it using the following:
I just wonder why I am getting this warning and how it can cause issues in my program and how to avoid this (instead of filtering the warning indeed)
(May-04-2018, 09:03 PM) nilamo Wrote: I can’t imagine it’d cause any issues in your code, unless you do it a lot (a LOT), and then it might slow your program down a bit.
I also can’t imagine how that’s happening without you purposefully reloading the module, though, as they’re cached. So just importing it multiple times wouldn’t cause a reload.
Thanks! So I just found this option in spyder which says:
«User Module Reloader (UMR): UMR forces Python to reload modules which were imported when executing a file in a Python or IPython console with the runfile function.»
And I deactivated it and now it works perfectly! Now my question is, why would somebody need this option?! Like why would I need to reload a module if it is already imported when I was executing the file?
Модули Python – примеры создания, импорта и использования
Модулем python может быть любой программный файл python, который содержит код, включая функции, класс или переменные python. Другими словами, мы можем сказать, что файл кода Python, сохраненный с расширением(.py), рассматривается как модуль. У нас может быть исполняемый код внутри модуля python.
Модули в Python отличаются маневренностью в логической организации кода. Чтобы использовать функциональность одного модуля в другом, мы должны импортировать конкретный модуль.
Создадим модуль с именем file.py, который содержит функцию func, которая содержит код для вывода некоторого сообщения на консоль.
Необходимо включить этот модуль в наш основной модуль, чтобы вызвать метод displayMsg(), определенный в модуле с именем file.
Загрузка модуля в код Python
Нам нужно загрузить модуль в код Python, чтобы использовать его функции. Python предоставляет два типа операторов:
Оператор импорта
Оператор импорта используется для импорта всех функций одного модуля в другой. Здесь мы должны заметить, что мы можем использовать функциональность любого исходного файла Python, импортировав этот файл в качестве модуля в другой исходный файл Python.
Мы можем импортировать несколько модулей с помощью одного оператора импорта, но модуль загружается один раз, независимо от того, сколько раз он был импортирован в наш файл.
Синтаксис для использования оператора импорта приведен ниже.
Следовательно, если нам нужно вызвать функцию displayMsg(), определенную в файле file.py, мы должны импортировать этот файл как модуль в наш модуль, как показано в примере ниже.
Оператор from-import
Вместо того, чтобы импортировать весь модуль, в python имеется возможность импортировать только определенные атрибутов модуля. Это можно сделать с помощью from-import оператора. Синтаксис для использования оператора from-import приведен ниже.
Рассмотрим следующий модуль, называемый calculation, который содержит три функции: суммирование, умножение и деление.
Оператор from … import всегда лучше использовать, если мы заранее знаем атрибуты, которые нужно импортировать из модуля. Это не позволяет нашему коду быть тяжелее. Мы также можем импортировать все атрибуты из модуля, используя *.
Рассмотрим следующий синтаксис.
Переименование модуля
Python предоставляет нам возможность импорта некоторого модуля с определенным именем, чтобы мы могли использовать его имя для этого модуля в нашем исходном файле python.
Синтаксис для переименования модуля приведен ниже.
Использование функции dir()
Функция dir() возвращает отсортированный список имен, определенных в переданном модуле. Этот список содержит все подмодули, переменные и функции, определенные в этом модуле.
Рассмотрим следующий пример.
Функция reload()
Как мы уже говорили, модуль загружается один раз независимо от того, сколько раз он был импортирован в исходный файл python. Однако, если вы хотите перезагрузить уже импортированный модуль, чтобы повторно выполнить код верхнего уровня, python предоставляет нам функцию reload(). Синтаксис использования функции reload() приведен ниже.
Например, чтобы перезагрузить вычисление модуля, определенное в предыдущем примере, мы должны использовать следующую строку кода.
Объем переменных
В Python переменные связаны с двумя типами областей видимости. Все переменные, определенные в модуле, содержат глобальную область видимости до тех пор, пока она не определена в функции.
Все переменные, определенные внутри функции, содержат локальную область видимости, которая ограничена самой этой функцией. Мы не можем получить глобальный доступ к локальной переменной.
Если две переменные определены с одним и тем же именем с двумя разными областями действия, т. е. локальной и глобальной, то приоритет всегда будет отдаваться локальной переменной.
Рассмотрим следующий пример.
Пакеты Python
Пакеты в python облегчают разработчикам среду разработки приложений, предоставляя иерархическую структуру каталогов, в которой пакет содержит подпакеты, модули и подмодули. Пакеты используются для эффективной категоризации кода уровня приложения.
Создадим пакет с именем «Сотрудники» в вашем домашнем каталоге пошагово.
1. Создайте каталог с именем Сотрудники / home.
2. Создайте исходный файл python с именем ITEmployees.py / home / Employees.
3. Аналогичным образом создайте еще один файл python с именем BPOEmployees.py и функцию getBPONames().
4. Теперь каталог «Сотрудники», который мы создали на первом шаге, содержит два модуля Python. Чтобы сделать этот каталог пакетом, нам нужно включить сюда еще один файл, то есть __init__.py, который содержит операторы импорта модулей, определенных в этом каталоге.
5. Теперь каталог «Сотрудники» стал пакетом, содержащим два модуля Python. Здесь мы должны заметить, что мы должны создать __init__.py внутри каталога, чтобы преобразовать этот каталог в пакет.
6. Чтобы использовать модули, определенные внутри пакета Employees, мы должны импортировать их в наш исходный файл python. Давайте создадим простой исходный файл Python в нашем домашнем каталоге(/ home), который использует модули, определенные в этом пакете.
Внутри пакетов могут быть подпакеты. Мы можем вкладывать пакеты до любого уровня в зависимости от требований приложения.
На следующем изображении показана структура каталогов системы управления библиотекой приложений, которая содержит три подпакета: Admin, Librarian и Student. Подпакеты содержат модули Python.
How do I unload (reload) a Python module?
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What’s the best way do do this?
21 Answers 21
You can reload a module when it has already been imported by using importlib.reload() :
I think that this is what you want. Web servers like Django’s development server use this so that you can see the effects of your code changes without restarting the server process itself.
To quote from the docs:
As you noted in your question, you’ll have to reconstruct Foo objects if the Foo class resides in the foo module.
In Python 3.0–3.3 you would use: imp.reload(module)
The BDFL has answered this question.
It can be especially difficult to delete a module if it is not pure Python.
You can use sys.getrefcount() to find out the actual number of references.
Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown «empty» (containing nothing) module should be garbage collected after
as the third reference is an artifact of the getrefcount() function.
If you have one-way dependencies, you must also reload all modules that depend on the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.
If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can’t do this with reload() because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.
It’s probably best to restart the server. 🙂
How to reload all imported modules?
I have several modules, I would like to reload without having to restart Sublime Text, while I am developing a Sublime Text package.
I am running Sublime Text build 3142 which comes with python3.3 running continuously its packages/plugins. However while developing a plugin, I import a third part module I added to path as:
But when I edit the source code of the module six I need to close and open Sublime Text again, otherwise Sublime Text does not gets the changes to the six python module.
Some code I have tried so far:
2 Answers 2
sys.modules is a dictionary that maps the string names of modules to their references.
To reload modules, you can loop over the returned list from above and call importlib.reload on each one:
I imagine in most situations, you want to reload only the modules that you yourself are editing. One reason to do this is to avoid expensive reloads, and another is hinted in @dwanderson’s comment, when reloading pre-loaded modules might be sensitive to the order in which they are loaded. It’s particularly problematic to reload importlib itself. Anyways, the following code reloads only the modules imported after the code is run:
The code is not exactly correct because of the except block, but it seems robust enough for my own purposes (reloading imports in a REPL).






