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:
Модули 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.
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?
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. 🙂
Reloading Python modules
Problem
The GUI for PyUnit presented an unusual challenge; every time it is asked to run a test, it must ensure that the modules referenced by the test are completely reloaded. That way, the GUI can be left running while tests are altered and problems fixed.
It sounds deceptively simple, and proved to be rather fiddly. This page describes what I discovered.
Wrong solution 1: reload() all modules
The first obvious solution was to simply reload() all modules. This is easily accomplished using the following code snippet, or similar:
One could be clever, and only reload recent or non-built-in modules, but the idea remains the same. The reason this solution is wrong is illustrated by the following scenario. Consider two modules ‘a’ and ‘b’:
and some code that uses them:
Now imagine that we change ‘a.py’:
Here, the second assertion fails! This is due to the order in which the reload() calls were made. Grab the example code and try it for yourself.
Of course, the problem is that the modules are chained together by their imports.
Wrong solution 2: reload() all modules twice
«Aha!» one might say, «Why not reload those modules twice?» Indeed, in the above case this works fine, but it is not a general solution:
If these modules were imported, then ‘a.value’ changed in file ‘a.py’, the modules would need to be reloaded three times before ‘c.value’ would match ‘a.value’.
Wrong solution 3: using the ‘ihooks’ package
At first glance, it appears that using a custom importer built using the ‘ihooks’ package should allow us to explicitly load every module afresh each time it is imported.
This could be achieved by simply not checking ‘sys.modules’ for pre-loaded modules. However, mutually referencing modules cause an endless loop if the ‘sys.modules’ shortcut is omitted.
Storing the modules in a list other than ‘sys.modules’ also caused problems.
Correct solution: a ‘rollback importer’
Taking a step back, the situation is as follows:
The solution is to draw a line in the ‘module sand’ before loading and using the modules, then roll back to that point before re-running the code. This is accomplished, in PyUnit, by the following class:
RollbackImporter instances install themselves as a proxy for the built-in __import__ function that lies behind the ‘import’ statement. Once installed, they note all imported modules, and when uninstalled, they delete those modules from the system module list; this ensures that the modules will be freshly loaded from their source code when next imported.
The rollback importer is used as follows in the PyUnit GUI (modified for clarity):