static method in Python not working - python

I'm learning by my self Python and I have a mind blowing issue, because I don't understand why is not working. I'm using PyDev and I've download version 2 of Python. I have this code:
class Utils:
#staticmethod
def hello():
print "Hi! I'm the Utils class"
Utils.hello() #Hi! I'm the Utils class
and everything is working fine at this point. But if I import the Utils class and call the static method from another module...
import Utils
Utils.hello()
I get this error:
Traceback (most recent call last):
File "C:\Users\migugonz\Desktop\Docs\Per Folder\WorkSpacePy\Rosalind\src\bioinformatics\stronghold\Pruebas.py", line 40, in <module>
Utils.hello()
AttributeError: 'module' object has no attribute 'hello'
I thing it can't be a big deal, but I've been searching a solution and as long I know this shlould be work.

I believe you need to do Utils.Utils.hello()
or import like from Utils import Utils

Related

"Most likely due to circular import" in Python

import threading
import time
start = time.perf_counter()
def do_something():
print("Sleeping in 1 second")
time.sleep(1)
print("Done sleeping")
t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)
finish = time.perf_counter()
print(f"Finished in {round(finish-start,1)} seconds(s) ")
Does anyone know why this piece of code returns this error when run and how to fix it?
Traceback (most recent call last):
File "c:/Users/amanm/Desktop/Python/Python Crash Course/threading.py", line 1, in <module>
import threading
File "c:\Users\amanm\Desktop\Python\Python Crash Course\threading.py", line 12, in <module>
t1 = threading.Thread(target=do_something)
AttributeError: partially initialized module 'threading' has no attribute 'Thread' (most likely due to a circular import)
When I run this code in normal IDLE it seems to work but it doesn't work in Visual Studio Code.
It seems like the program file you have created is named threading.py, and you are importing a module also called threading. This causes a circular import because your file is shadowing the built-in module.
Please rename your program (e.g., threading_example.py).
I solved my problem, example code:
Main.py
if __name__ == "__main__":
import package2
pack2class = package2.Package2(main=self)
package2.py
import Main
class Package2(object):
def __init__(self, main:Main.MainClass): # for suggestion code
pass # your codes ...
When importing modules, python checks the files in your current working directory first, before checking other built-in modules. So, you probably have a file named threading.py which doesn't have the necessary attributes. In other words, you made a circular import.

Module 'a' has no attribute 'b' while importing module from same directory

I have following directory structure in my Python project:
- dump_specs.py
/impa
- __init__.py
- server.py
- tasks.py
I had a problem with circular references. dump_specs.py needs a reference to app from server.py. server.py is a Flask app which needs a references to celery tasks from tasks.py. So dump_specs.py looks like:
#!/usr/bin/env python3
import impa.server
def dump_to_dir(dir_path):
# Do something
client = impa.server.app.test_client()
# Do the rest of things
impa/server.py looks like:
#!/usr/bin/env python3
import impa.tasks
app = Flask(__name__)
# Definitions of endpoints, some of them use celery tasks -
# that's why I need impa.tasks reference
And impa/tasks.py:
#!/usr/bin/env python3
from celery import Celery
import impa.server
def make_celery(app):
celery = Celery(app.import_name,
broker=app.config['CELERY_BROKER_URL'],
backend=app.config['CELERY_RESULT_BACKEND'])
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(impa.server.app)
When I'm trying to dump specs with ./dump_specs.py I've got an error:
./dump_specs.py specs
Traceback (most recent call last):
File "./dump_specs.py", line 9, in <module>
import impa.server
File "/build/impa/server.py", line 23, in <module>
import impa.tasks
File "/build/impa/tasks.py", line 81, in <module>
celery = make_celery(impa.server.app)
AttributeError: module 'impa' has no attribute 'server'
And I can't understand what's wrong. Could someone explain what's happening and how to get rid of this error?
If I have managed to reproduce your problem correctly on my host, it should help youto insert import impa.tasks into dump_specs.py above import impa.server.
The way your modules depend on each other, the loading order is important. IIRC (the loading machinery is described in greater details in the docs), when you first try to import impa.server, it will on line 23 try to import impa.tasks, but import of impa.server is not complete at this point. There is import impa.server in impa.tasks, but we do not got back and import it at this time (we'd otherwise end up in a full circle) and continue importing impa.tasts until we want to access impa.server.app, but we haven't gotten to the point we could do that yet, impa.server has not been imported yet.
When possible, it would also help if the code accessing another module in your package wasn't executed on import (directly called as part of the modules instead of being in a function or a class which would be called/used after the imports have completed).

How to solve this Python import circular reference

I have a class JCheq, with a static var named 'logger'.
JCheq imports module printing_systems, but I need to use JCheq.logger from printing_systems.
My code does not compile after I put import JCheq in printing_systems.py.
jcheq.py
from printing_systems import printing_systems
from logger import logger
class JCheq:
logger = logger.Logger('logs/jcheq.log', loglevel=logger.Logger.INFO)
def __init__(self):
pass
...
printing_systems/printing_systems.py
from jcheq import JCheq
class WinLPR:
def __init__(self):
pass
#staticmethod
def send(spool, params):
temp_dir = tempfile.mkdtemp()
try:
JCheq.logger.log('Creando archivo temporal en dir: ' + temp_dir, logger.Logger.TRACE)
Error trace:
Traceback (most recent call last):
File "/home/jsivil/Desktop/Proyectos/UNPAZ/jcheq/jcheq/jcheq.py", line 12, in <module>
from printing_systems import printing_systems
File "/home/jsivil/Desktop/Proyectos/UNPAZ/jcheq/jcheq/printing_systems/printing_systems.py", line 7, in <module>
from jcheq import JCheq
File "/home/jsivil/Desktop/Proyectos/UNPAZ/jcheq/jcheq/jcheq.py", line 12, in <module>
from printing_systems import printing_systems
ImportError: cannot import name 'printing_systems'
Moving the import statement in the function is commonly used to solve circular imports. It is handy in cases when restructuring your application would be too costly (if useful at all).
Another solution would be to move JCheq.logger into its own module that both jcheq.py and printing_systems/printing_systems.py would import.
Or, you could make logger.Logger a factory function backed by some registry (or simply memoize it) so that it returns the same logger when the same arguments are given. This way, printing_system.py would simple import logger instead of importing jcheq.

Python: class not callable from separate file?

I have a class, robot, in a file called robot.py
I want to create a robot instance in my main script like so:
in robot.py:
class robot(object):
def __init__(self,pygame,screen_width,screen_height):
in main.py:
import pygame, sys, copy
import mouse
import robot
import menu
import button
from pygame.locals import *
...
size = [1200,900]
my_robot = robot(pygame,size[0]-400,size[1]-100)
error:
me:cup-robot Me$ python run.py
Traceback (most recent call last):
File "run.py", line 24, in <module>
my_robot = robot(pygame,size[0]-400,size[1]-100)
TypeError: 'module' object is not callable
how do I do this?
Two choices :
import robot and then prefix all with robot :
my_robot = robot.robot(pygame,size[0]-400,size[1]-100)
or
from robot import robot and then your code should work. But then, you can see that you won't be able to distinguish if robot is a module or the class, so you should not name the class and the file with the same name.
Change your import statement:
from robot import robot
You have robot defined both as a module (robot.py) as well as a class. You need to import the class from the module so it is publicly available.

Can someone explain this unexpected Python import behavior?

I've run into some behavior from Python 2.6.1 that I didn't expect. Here is some trivial code to reproduce the problem:
---- ControlPointValue.py ------
class ControlPointValue:
def __init__(self):
pass
---- ControlPointValueSet.py ----
import ControlPointValue
---- main.py --------------------
from ControlPointValue import *
from ControlPointValueSet import *
val = ControlPointValue()
.... here is the error I get when I run main.py (under OS/X Snow Leopard, if it matters):
jeremy-friesners-mac-pro-3:~ jaf$ python main.py
Traceback (most recent call last):
File "main.py", line 4, in <module>
val = ControlPointValue()
TypeError: 'module' object is not callable
Can someone explain what is going on here? Is Python getting confused because the class name is the same as the file name? If so, what is the best way to fix the problem? (I'd prefer to have my python files named after the classes that are defined in them)
Thanks,
Jeremy
I don't think it's unexpected. What you are basically doing is:
1) the first import in main.py imports the contents of ControlPointValue module into the global namespace. this produces a class bound to that name.
2) the second import in main.py imports the contents of ControlPointValueSet module into the global namespace. This module imports ControlPointValue module. This overwrites the binding in the global namespace, replacing the binding for that name from the class to the module.
To solve, I would suggest you not to import *, ever. Always keep the last module prefix. For example, if you have foo/bar/baz/bruf.py containing a class Frobniz, do
from foo.bar.baz import bruf
and then use bruf.Frobniz()
In addition to the other suggestions about star imports, don't name your module and your class the same. Follow pep8's suggestions and give your modules short all lower case names and name your classes LikeThis. E.g.
---- controlpoints.py ------
class ControlPointValue:
def __init__(self):
pass
---- valuesets.py ----
from controlpoints import ControlPointValue
---- main.py --------------------
from controlpoints import ControlPointValue
from valuesets import *
val = ControlPointValue()

Categories