Python Attribute error when using from main import x - python

So I have two files: main.py file and a debugModule.py. The debugModule.py file has a class named Debug(). This class has a method, update(), that I want to use in main.py. How would I do this?
In main I use import debugModule, debug = debugModule.Debug(), and then debug.update() in order to execute this method, however this just throws an error:
File "C:\Users\Nisse\workspace\Platformer\src\main.py", line 5, in <module>
debug = debugModule.Debug()
AttributeError: 'module' object has no attribute 'Debug'
I've looked around Stackoverflow for answers but I can't get it to work.
How can i use a function from another module in my main.py?
Edit: Turns out I completely messed up the names. Edited again, now they're correct.

Related

AttributeError: module 'openpyxl.cell' has no attribute 'get_column_letter'

when I try to run code regarding retrieving column letter from a number I keep getting the following error:
AttributeError: module 'openpyxl.cell' has no attribute 'get_column_letter'
This is the code I am trying to run:
print(openpyxl.cell.get_column_letter(26))
I expect this to run with no error.
Because this attribute has been moved to utils within this module, the way to call this without getting an error is to call it from its new location:
print(openpyxl.utils.cell.get_column_letter(26))
This should be working now.

Python circular reference importing doesn't work when using "as"

Let me first establish what working scenario.
main.py
module/file1.py
module/file2.py
main.py
import module.file1
print(module.file1)
module/file1.py
import module.file2
module/file2.py
import module.file1
Running python3 main.py gives me the following, which is fine.
<module 'module.file1' from '/project/module/file1.py'>
Now, if I change module/file2.py to have the following:
import module.file1 as testtt
I get this new output (error):
Traceback (most recent call last):
File "main.py", line 1, in <module>
import module.file1
File "/project/module/file1.py", line 1, in <module>
import module.file2
File "/project/module/file2.py", line 2, in <module>
import module.file1 as testtt
AttributeError: module 'module' has no attribute 'file2'
I'm guessing that python doesn't fully evaluate the imported module when simply importing, causing the circular reference to blow up only when you immediately use it within either of the two files.
I'd imagine I also would not get the error if I used the module in a function, since that would be evaluate when the function is actually called, like this:
import module.file1
def test():
print(module.file1)
What is the recommendation here? Should I just work to remove the circular reference? It seems like code smell anyway (existing code base).
Its an implementation detail. The import statement uses the __import__ function to do the work of finding and importing the module and then binds its returned module to the as testtt variable.
When doing a nested import like import module.file1 as testtt, __import__ returns the base module ("module"). Since the importer still needs to bind "file1" to the local namespace, it has to look up the submodule name "file1" on that object. Since the import of file1 is still in progress, it hasn't been bound to the "module" module yet.
It works in the import module.file1 case because file1 isn't bound to the local namespace and doesn't need a lookup.
There are many pitfalls with circular imports that will bedevil you throughout your code's life cycle. Good luck!
"import" is an executable statement, so you can just do the import inside the function
def test():
import module.file1
print(module.file1)

Python import error: 'module' object has no attribute 'x'

I am trying to do a python script that it is divided in multiple files, so I can maintain it more easily instead of making a very-long single file script.
Here is the directory structure:
wmlxgettext.py
<pywmlx>
|- __init__.py
|- (some other .py files)
|- <state>
|- __init__.py
|- state.py
|- machine.py
|- lua_idle.py
if I reach the main directory of my project (where the wmlxgettext.py script is stored) and if I try to "import pywmlx" I have an import error (Attribute Error: 'module' object has no attribute 'state')
Here is the complete error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/programmi/my/python/wmlxgettext/true/pywmlx/__init__.py", line 9, in <module>
import pywmlx.state as statemachine
File "/home/user/programmi/my/python/wmlxgettext/true/pywmlx/state/__init__.py", line 1, in <module>
from pywmlx.state.machine import setup
File "/home/user/programmi/my/python/wmlxgettext/true/pywmlx/state/machine.py", line 2, in <module>
from pywmlx.state.lua_idle import setup_luastates
File "/home/user/programmi/my/python/wmlxgettext/true/pywmlx/state/lua_idle.py", line 3, in <module>
import pywmlx.state.machine as statemachine
AttributeError: 'module' object has no attribute 'state'
Since I am in the "project main directory" pywmlx should be on PYTHONPATH (infact I have no troubles when I tried to import pywmlx/something.py)
I'm not able to figure where is my error and how to solve this problem.
Here is the pywmlx/__init__.py source:
# all following imports works well:
from pywmlx.wmlerr import ansi_setEnabled
from pywmlx.wmlerr import wmlerr
from pywmlx.wmlerr import wmlwarn
from pywmlx.postring import PoCommentedString
from pywmlx.postring import WmlNodeSentence
from pywmlx.postring import WmlNode
# this is the import that does not work:
import pywmlx.state as statemachine
Here is the pywmlx/state/__init__.py source:
from pywmlx.state.machine import setup
from pywmlx.state.machine import run
But I think that the real problem is somewhat hidden in the "imports" used by one (or all) python modules stored in pywmlx/state directory.
Here is the pywmlx/state/machine.py source:
# State is a "virtual" class
from pywmlx.state.state import State
from pywmlx.state.lua_idle import setup_luastates
import pywmlx.nodemanip as nodemanip
def addstate(self, name, value):
# code is not important for this question
pass
def setup():
setup_luastates()
def run(self, *, filebuf, fileref, fileno, startstate, waitwml=True):
# to do
pass
Finally here is the pywmlx/state/lua_idle.py source:
import re
import pywmlx.state.machine as statemachine
# State is a "virtual" class
from pywmlx.state.state import State
# every state is a subclass of State
# all proprieties were defined originally on the base State class:
# self.regex and self.iffail were "None"
# the body of "run" function was only "pass"
class LuaIdleState (State):
def __init__(self):
self.regex = re.compile(r'--.*?\s*#textdomain\s+(\S+)', re.I)
self.iffail = 'lua_checkpo'
def run(xline, match):
statemachine._currentdomain = match.group(1)
xline = None
return (xline, 'lua_idle')
def setup_luastates():
statemachine.addstate('lua_idle', LuaIdleState)
Sorry if I posted so much code and so many files... but I fear that the files, in directory, hides more than a single import problem, so I published them all, hoping that I could explain the problem avoiding confusion.
I think that I miss something about how import works in python, so I hope this question can be useful also to other programmers, becouse I think I am not the only one who found the official documentation very difficult to understand when explaining import.
Searches Done:
Not Useful: I am already explicitly using import x.y.z all times I need to import something
Not Useful: Even if the question asks about import errors, it seems not useful for the same reason as (1)
Not Useful: As far as I know, pywmlx should be located into PYTHONPATH since "current working directory" on my tests is the directory that contains the main python script and pywmlx directory. Correct me if I am wrong
Python does several things when importing packages:
Create an object in sys.modules for the package, with the name as key: 'pywmlx', 'pywmlx.state', 'pywmlx.state.machine', etc.
Run the bytecode loaded for that module; this may create more modules.
Once a module is fully loaded and it is located inside another package, set the module as an attribute of the parent module object. Thus the sys.modules['pywmlx.state'] module is set as the state attribute on the sys.modules['pywmlx'] module object.
That last step hasn't taken place yet in your example, but the following line only works when it has been set:
import pywmlx.state.machine as statemachine
because this looks up both state and machine as attributes first. Use this syntax instead:
from pywmlx.state import machine as statemachine
Alternatively, just use
import pywmlx.state.machine
and replace statemachine. everywhere else with pywmlx.state.machine.. This works because all that is added to your namespace is a reference to the sys.modules['pywmlx'] module object and the attribute references won't need to be resolved until you use that reference in the functions and methods.
You are having a circular import in your framework. Circular imports do not work well with aliases. When importing a module with an alias and then, during the circular import, importing it again without an alias, python complains. The solution is to not use aliases (the "import module as" syntax) but always use the full "import module" statement.

Python: cannot load class from my module

EDIT:
I couldn't use my own modules. It was a stupid waste of time. If you ever have the same problem, try reading this first:
http://docs.python-guide.org/en/latest/writing/structure/
I just started OOP with Python and I am confused by modules and classes.
I work with a Mac and I can write my own modules and load them from the site-packages folder.
Now I would like to create modules with useful classes.
import custom_module works.
But if custom_module has a class Custom_class, things don't work.
I tried doing:
(EDIT: I am sorry, I am removing old code which was made up, this is what I just used and doesn't work)
in custommodule.py:
class Customclass:
def __init__(self, name):
self.name = name
This module loads without errors.
Then I get:
new = custommodule.Customclass('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Customclass'
BTW, I started trying to do this using code from this tutorial
I was not able to get over this. Please advise, I must be doing something wrong.
With this file layout
site-packages/custommodule/__init__.py
site-packages/custommodule/custommodule.py
you are creating a package named custommodule that contains a module also named custommodule. Your code needs to look like
import custommodule
# or more specifically,
# import custommodule.custommodule
new = custommodule.custommodule.Customclass('foo')
or
from custommmodule import custommodule
new = custommodule.Customclass('foo')
You can also put custommodule.py directly in site-packages to avoid creating the package, in which case your original code should work.
For me, at least, this works from mod_name import ClassName
When I run this code I don't get any errors. Hope this helped
EDIT: also make sure that the module you want to import is in the project directory. If you view the left panel in the images both modules are in Stack. I hope this is obvious but, the class needs to be in the module you import as well. Make sure that the class you're importing does not import the class your importing in because then you get circular dependencies.
Try this way
File custommodule.py in the directory custommodule
class Customclass:
def __init__(self, name):
self.name = name
File __init__.py int he custommodule directory
from .custommodule import CustomClass
Note the dot before custommodule. This force the init to load the module from the same directory.
Without the dot, it work under python2 but not under python3

Python NameError when attempting to use a user-defined class

I'm getting a weird instance of a NameError when attempting to use a class I wrote. In a directory, I have the following file structure:
dir/
ReutersParser.py
test.py
reut-xxx.sgm
Where my custom class is defined in ReutersParser.py and I have a test script defined in test.py.
The ReutersParser looks something like this:
from sgmllib import SGMLParser
class ReutersParser(SGMLParser):
def __init__(self, verbose=0):
SGMLParser.__init__(self, verbose)
... rest of parser
if __name__ == '__main__':
f = open('reut2-short.sgm')
s = f.read()
p = ReutersParser()
p.parse(s)
It's a parser to deal with SGML files of Reuters articles. The test works perfectly. Anyway, I'm going to use it in test.py, which looks like this:
from ReutersParser import ReutersParser
def main():
parser = ReutersParser()
if __name__ == '__main__':
main()
When it gets to that parser line, I'm getting this error:
Traceback (most recent call last):
File "D:\Projects\Reuters\test.py", line 34, in <module>
main()
File "D:\Projects\Reuters\test.py", line 19, in main
parser = ReutersParser()
File "D:\Projects\Reuters\ReutersParser.py", line 38, in __init__
SGMLParser.__init__(self, verbose)
NameError: global name 'sgmllib' is not defined
For some reason, when I try to use my ReutersParser in test.py, it throws an error that says it cannot find sgmllib, which is a built-in module. I'm at my wits' end trying to figure out why the import won't work.
What's causing this NameError? I've tried importing sgmllib in my test.py and that works, so I don't understand why it can't find it when trying to run the constructor for my ReutersParser.
Your problem is not your code, but what you run it in. If you read the error and the code it displays closely:
File "D:\Projects\Reuters\ReutersParser.py", line 38, in __init__
SGMLParser.__init__(self, verbose)
NameError: global name 'sgmllib' is not defined
you'll notice there's no reference to 'sgmllib' on the line that Python thinks produced this error. That means one of two things: either the error didn't originate there (and Python is quite confused), or the code that's being displayed is not the code that is being executed. The latter is quite common when you, for example, run your code in an IDE that doesn't restart the Python interpreter between code executions. It will execute your old code, but when displaying the traceback will show the new code. I'm guessing you did sgmllib.SGMLParser.__init__(self, verbose) on that line at some point in the past.
The reason it was fixed by renaming the class is probably that you did something -- like editing the code -- that caused the IDE to either restart the interpreter, properly clean it up or (by accident) reloaded the right module the right way for it to see the new code. Since you name your module after your class (which is bad style, by the way) I assume you renamed your module when you renamed your class, and so your IDE picked up the new code this time. Until the next time the same thing happens, of course.

Categories

Resources