Python 3.5.1 import class in the same directory - python

So I am having trouble importing classes in the same directory and getting them to work properly.
I currently have the following hiearchy
BBDriver.py
bbsource:
BouncyBallEnv.py
Console.py
resources:
misc:
objects:
Ball.py
Platform.py
My problem is between the 2 files in the bbsource directory. I have figured out how to get access from the bbsource directory down to the classes in the objects directory and vice versa but when I try to from BouncyBallEnv import BouncyBallEnv in the Console class I get the following error:
File "E:\PycharmProjects\BouncyBallPythonV0\bbsource\Console.py", line 5, in
from BouncyBallENV import BouncyBallEnv
ImportError: cannot import name 'BouncyBallEnv'
I have tried several things like:
from bbsource import BouncyBallEnv
from bbsource.BouncyBallEnv import BouncyBallEnv
But I can't get it to work.
The only time I could get it to work is when I did the following:
import bbsource.BouncyBallEnv
#Extra
print(bbsource.BouncyBallEnv.BouncyBallEnv.WIDTH)
But there must be a better way to do it than that so that I wouldn't have to type that lengthy statement that is in the print statement every time that I want to use a static variable in BouncyBallEnv.
I am still quite confused on how the Python importing works so I'm not sure how to go about doing this. Thank you.
NOTE: Running Python 3.5.1

the thing you need is aliases :
import bbsource.BouncyBallEnv as bbe
#Extra
print(bbe.WIDTH)
and you can't import a module with the from ... import ... syntax. Only attributes. It work like this :
import <module> [as <alias>]
or
from <module> import <attribute> [, <attribute2>...] # import some attributes
from <module> import * # import everything
with the second one, you could have done :
from bbsource.BouncyBallEnv import WIDTH
# the variable WIDTH is directly loaded : watch out for collision !
print(WIDTH)

It is abosolue_import rule.
try
from .BouncyBallENV import BouncyBallEnv
to access module in relative position.
besides, there should be an __init__.py file under bbsource directory

Related

How to import python module as a specific reference?

I had a file at db/connection.py. I moved the file and now the path is project/db/connection.py.
Previously I imported that file using this syntax:
import db.connection
And somewhere in the code I had access to the file:
db.connection.open_connection()
Since now the file is moved, I know only two options to import the file: using import and from import keywords. But both of them will change the reference to the file. I'll show you what I mean.
If I use import:
import project.db.connection
Then the new reference is project.db.connection and I need to change the code that accesses the file as well, so that it becomes:
project.db.connection.open_connection()
If I use from import:
from project.db import connection
The same problem, but now the reference is connection.
I thought I could do that:
from project import db.connection
But python gives me an error at that line of code:
from project import db.connection
^
SyntaxError: invalid syntax
So if it's possible, how to import the new file having the reference db.connection, so I don't need to change the code that accesses that file?
from project import db
Maybe you need to add __init__.py file in project and in project/db.

ImportError attempted relative import with no known parent

Based on some answers I try to be more specific.
I want to import the print and the models AND code in my main.py
I know the question gets asked a lot, but still I could not figure out whats wrong with my code!
I have a project directory like this
-project
--__init__py
--main.py
--print.py
--requests
--__init__.py
--models.py
--code.py
i want to import from print.py and * from requests
Therefore I tried to add these lines in main.py
from . import print
#or
import print
#for requests I tried
import os.path
import sys
sys.path.append('./requests')
from requests import *
all of those lines cause the same ImportError attempted relative import with no known parent ,
using Python 39
anyone an idea where the problem is?
I am very confused that this seems not to work, was it possible in older versions?
You should definitely not be doing anything with sys.path. If you are using a correct Python package structure, the import system should handle everything like this.
From the directory structure you described, project would be the name of your package. So when using your package in some external code you would do
import package
or to use a submodule/subpackage
import project.print
import project.requests
and so on.
For modules inside the package you can use relative imports. When you write
i want to import from print.py and * from requests Therefore I tried
it's not clear from where you want to import them, because this is important for relative imports.
For example, in project/main.py to import the print module you could use:
from . import print
But if it's from project/requests/code.py you would use
from .. import print
As an aside, "print" is probably not a good name for a module, since if you import the print module it will shadow the print() built-in function.
Your main file should be outside the 'project'-directory to use that as a package.
Then, from your main file, you can import using from project.print import ....
Within the project-package, relative imports are possible.

Cannot import file from same directory

Trying to import a file (meleeWeapons.py) into my main file (main.py) but it does not seem to be working.
The file directy is as follows
Domination
|_main.py
|_meleeWeapons.py
|_test.py
When I load from Domination import meleeWeapons or from . import meleeWeapons into main.py, trying to load any objects from meleeWeapons into main doesnt work, flagging "myObject" is not defined. When I do the from Domination import meleeWeapons approach, the error "Import "Dominations" could not be resolved"
When you import things from a local module, you put the module name first, then the symbols ("objects") second
from meleeWeapons import Domination
If you want to import everything into the global namespace (you rarely, if ever, want to do this), then do this:
from meleeWeapons import *
If you want import the module itself, and using meleeWeapons.Dominion to access Dominion (or any other symbol), then just do a standard import:
import meleeWeapons
You can also give the module an alias:
import meleeWeapons as mW
You're using the wrong syntax. You need
import meleeWeapons
What you did was to tell Python to look in the file Domination.py, and return the symbol meleeWeapons.

Cannot import function from another file

I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.

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.

Categories

Resources