Python NameError: Name 'get_tool_versions' not defined - python

I am trying to run a cmd script which calls a setenv.py file. This file has a function which says,
import build_cfg
tool_versions = get_tool_versions()
env_var_list = get_env_var()
which I believe is importing the build_cfg module.
build_cfg in turn has get_tool_versions and get_env_vars functions defined.
Anyway, when I run my script I get an error :
File "setenv.py", line 172, in <module>
tool_versions = get_tool_versions ()
NameError: name 'get_tool_versions' is not defined
I am relatively new to python. Could you please tell me what I am doing wrong?

The error message says it all: The function get_tool_versions does not exist in the global namespace.
To solve this problem you have to find out where get_tool_versions is defined and import it from there. If it is defined in build_cfg you can do it like this:
import build_cfg
tool_versions = build_cfg.get_tool_versions()
...
or
from build_cfg import get_tool_versions
tool_versions = get_tool_versions()
...

Related

Creating importable Python 3 package / module

I am having trouble creating an importable Python package/library/module or whatever the right nomenclature is. I am using Python 3.7
The file structure I am using is:
Python37//Lib//mypackage
mypackage
__init__.py
mypackage_.py
The code in __init__.py is:
from mypackage.mypackage_ import MyClass
The code in mypackage_.py is:
class MyClass:
def __init__(self, myarg = None):
self.myvar = myarg
And from my desktop I try running the following code:
import mypackage
x = MyClass(None)
But get the following error:
Traceback (most recent call last):
File "C:\Users\***\Desktop\importtest.py", line 3, in <module>
x = MyClass(None)
NameError: name 'MyClass' is not defined
You haven't imported the name MyClass into your current namespace. You've imported mypackage. To access anything within mypackage, you need to prefix the name with mypackage.<Name>
import mypackage
x = mypackage.MyClass(None)
As #rdas says, you need to prefix the name with mypackage.<Name>.
I don't recommend doing this, but you can wildcard import in order to make x = MyClass(None) work:
from mypackage import *
Now, everything from mypackage is imported and usable in the current namespace. However, you have to be careful with wildcard imports because they can create definition conflictions (if multiple modules have the same name for different things).

ImportError on Python

I'm new to python and I'm having this problem that I can't figure it out.
My file structure is:
enter image description here
On Criador.py I have several functions, for example:
def doSomething():
pass
def doSomethingElse():
pass
and Im trying to use one of this functions on the Controller.py file:
The first thing I did was, on the Controller.py:
import Controller.Criador
and then tried to use that function as:
Controller.Criador.doSomething()
After running Controller.py, I got this error:
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
I tried several other things, like:
from . import Criador
or
from Controller.Criador import doSomething
or
from Controller import Criador
and nothing helped, just changed the errors to:
ImportError: cannot import name 'Criador'
and
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
and
ImportError: cannot import name 'Criador'
Can someone give me a light about this? I'm using PyCharm and it does not give me any error when I declare the imports, only when I run the file
If Controller.py and Criador.py are in the same folder, you can do this inside Controller.py:
import Criador
Criador.doSomething()

Package import failure in Python 3.5

I have the following folder structure:
/main
main.py
/io
__init__.py
foo.py
In Python 2.7 I would write the following in main.py:
import io.foo
or
from io.foo import *
wheareas in Python 3.5 I get an import error:
Traceback (most recent call last):
File "./main.py", line 6, in <module>
import io.foo
ImportError: No module named 'io.foo'; 'io' is not a package
I couldn't find any help so far.
io is a built-in module. Don't name your local packages the same as a built-in module.
While #ErikCederstrand's answer is correct and probably sufficient for you, I was curious as to why it failed so I went digging through cpython's source. So for any future visitors, here's what I found.
The function where it's failing is here: https://github.com/python/cpython/blob/3.4/Lib/importlib/_bootstrap.py#L2207
On line 2209, it checks to see if the parent module has been loaded:
parent = name.rpartition('.')[0] # Value of 'io'
Since it has loaded the builtin io module, it continues on like normal. After the if returns false, it goes on to assign parent module which again is set to "io":
if name in sys.modules:
return sys.modules[name]
parent_module = sys.modules[parent]
The next lines are what cause the failure, and it's because builtin modules (io anyway) don't have a __path__ instance variable. The exception you see raised here are ultimately what you're seeing when you run it:
try:
path = parent_module.__path__
except AttributeError:
msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
raise ImportError(msg, name=name)
If you change your module name like Erik says, then step through this whole process, you can see the call to get parent_module.__path__ works like it's supposed to and everything's happy.
So, tldr: you've tricked the import system into thinking it's already loaded your custom module, but when it goes to try and use it like a custom module it fails because it's actually the builtin io.
EDIT: It looks like __path__ is set here after it goes through a normal import process in init_module_attrs:
if _override or getattr(module, '__path__', None) is None:
if spec.submodule_search_locations is not None:
try:
module.__path__ = spec.submodule_search_locations
except AttributeError:
pass

python 'module' - for png tiles out of my folder [duplicate]

File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__
self.serv = socket(AF_INET,SOCK_STREAM)
TypeError: 'module' object is not callable
Why am I getting this error?
I'm confused.
How can I solve this error?
socket is a module, containing the class socket.
You need to do socket.socket(...) or from socket import socket:
>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>
This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.
Here is a way to logically break down this sort of error:
"module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
"The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
I should print out what socket is and check print(socket)
Assume that the content of YourClass.py is:
class YourClass:
# ......
If you use:
from YourClassParentDir import YourClass # means YourClass.py
In this way, you will get TypeError: 'module' object is not callable if you then tried to call YourClass().
But, if you use:
from YourClassParentDir.YourClass import YourClass # means Class YourClass
or use YourClass.YourClass(), it works.
Add to the main __init__.py in YourClassParentDir, e.g.:
from .YourClass import YourClass
Then, you will have an instance of your class ready when you import it into another script:
from YourClassParentDir import YourClass
Short answer: You are calling a file/directory as a function instead of real function
Read on:
This kind of error happens when you import module thinking it as function and call it.
So in python module is a .py file. Packages(directories) can also be considered as modules.
Let's say I have a create.py file. In that file I have a function like this:
#inside create.py
def create():
pass
Now, in another code file if I do like this:
#inside main.py file
import create
create() #here create refers to create.py , so create.create() would work here
It gives this error as am calling the create.py file as a function.
so I gotta do this:
from create import create
create() #now it works.
Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too.
My zig was that I was doing the following:
from mypackage.bin import myscript
...
myscript(...)
when my zag needed to do the following:
from mypackage.bin.myscript import myscript
...
myscript(...)
In summary, double check your package and module nesting.
What I am trying to do is have a scripts directory that does not have the *.py extension, and still have the 'bin' modules to be in mypackage/bin and these have my *.py extension. I am new to packaging, and trying to follow the standards as I am interpreting them. So, I have at the setup root:
setup.py
scripts/
script1
mypackage/
bin/
script1.py
subpackage1/
subpackage_etc/
If this is not compliant with standard, please let me know.
It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.
Or you've got an import socket after your from socket import *:
>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'module' object is not callable
I know this thread is a year old, but the real problem is in your working directory.
I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :)
Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).
When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.
Traceback (most recent call last):
File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable
For example
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule]
},
# ...
)
Should have been
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule:main]
},
# ...
)
So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__': block. This will not make the module callable.
I faced the same problem. then I tried not using
from YourClass import YourClass
I just copied the whole code of YourClass.py and run it on the main code (or current code).it solved the error
you are using the name of a module instead of the name of the class
use
import socket
and then
socket.socket(...)
its a weird thing with the module, but you can also use something like
import socket as sock
and then use
sock.socket(...)
I guess you have overridden the builtin function/variable or something else "module" by setting the global variable "module". just print the module see whats in it.
Here's a possible extra edge case that I stumbled upon and was puzzled by for a while, hope it helps someone:
In some_module/a.py:
def a():
pass
In some_module/b.py:
from . import a
def b():
a()
In some_module/__init__.py:
from .b import b
from .a import a
main.py:
from some_module import b
b()
Then because when main.py loads b, it goes via __init__.py which tries to load b.py before a.py. This means when b.py tries to load a it gets the module rather than the function - meaning you'll get the error message module object is not callable
The solution here is to swap the order in some_module/__init__.py:
from .a import a
from .b import b
Or, if this would create a circular dependency, change your file names to not match the functions, and load directly from the files rather than relying on __init__.py
I got the same error below:
TypeError: 'module' object is not callable
When calling time() to print as shown below:
import time
print(time()) # Here
So, I called time.time() as shown below:
import time
print(time.time()) # Here
Or, I imported time from time as shown below:
from time import time # Here
print(time())
Then, the error was solved:
1671301094.5742612
I had this error when I was trying to use optuna (a library for hyperparameter tuning) with LightGBM. After an hour struggle I realized that I was importing class directly and that was creating an issue.
import lightgbm as lgb
def LGB_Objective(trial):
parameters = {
'objective_type': 'regression',
'max_depth': trial.suggest_int('max_depth', 10, 60),
'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
'data_sample_strategy': 'bagging',
'num_iterations': trial.suggest_int('num_iterations', 50, 250),
'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0),
'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
}
'''.....LightGBM model....'''
model_lgb = lgb(**parameters)
model_lgb.fit(x_train, y_train)
y_pred = model_lgb.predict(x_test)
return mse(y_test, y_pred, squared=True)
study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression')
study_lgb.optimize(LGB_Objective, n_trials=200)
Here, the line model_lgb = lgb(**parameters) was trying to call the cLass itself.
When I digged into the __init__.py file in site_packages folder of LGB installation as below, I identified the module which was fit to me (I was working on regression problem). I therefore imported LGBMRegressor and replaced lgb in my code with LGBMRegressor and it started working.
You can check in your code if you are importing the entire class/directory (by mistake) or the target module within the class.
from lightgbm import LGBMRegressor
def LGB_Objective(trial):
parameters = {
'objective_type': 'regression',
'max_depth': trial.suggest_int('max_depth', 10, 60),
'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
'data_sample_strategy': 'bagging',
'num_iterations': trial.suggest_int('num_iterations', 50, 250),
'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0),
'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
}
'''.....LightGBM model....'''
model_lgb = LGBMRegressor(**parameters) #here I've changed lgb to LGBMRegressor
model_lgb.fit(x_train, y_train)
y_pred = model_lgb.predict(x_test)
return mse(y_test, y_pred, squared=True)
study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression')
study_lgb.optimize(LGB_Objective, n_trials=200)
A simple way to solve this problem is export thePYTHONPATH variable enviroment. For example, for Python 2.6 in Debian/GNU Linux:
export PYTHONPATH=/usr/lib/python2.6`
In other operating systems, you would first find the location of this module or the socket.py file.
check the import statements since a module is not callable.
In Python, everything (including functions, methods, modules, classes etc.) is an object.

Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name

Categories