invalid syntax for unknown reason - python-3.x

I'm doing some django stuffs using vs code and this error in the line 3 ("from") happend for no reason.
from django.urls import path
from * import views
urlpatterns = [path(" ",views,name="home")]

Your second import seems to be incorrect.
The syntax should be:
from <module> import <library / *>
In your case, it should be:
from views import *
That should be correct, as long as the views module do exist and can be found by python.

You cannot import like from *. Python expects a package name after from. If you are trying to import it from the relative path it might be something like
from . import views
Its a valid syntax error, and it did not happen for no-reason!

Related

how to import a python class from different mains at different level of indentation

I am trying to structure a program with several modules as it is customary for python.
I have several modules containing classes and functions, and a usual main entry point.
Now I have built a different main that serves another (larger) purpose.
My structure is something like this:
-----main.py
|---module1
| |---subMain.py
| |---script1.py
| |---script2.py
| |---submodule1
| |---script3.py
|---module2
|---script4.py
Currently subMain.py imports all scripts from module1 with no problems.
Yet, if I try to run main.py by importing module1 files it fails.
#This works
#subMain.py
from script1 import *
#########
#script1.py
from submodule1.script3 import *
#This does not work
#main.py
#So far so good
from module1.script1 import *
#########
#script1.py
#this fails
from submodule1.script3 import *
#If I change it to the following, it works
from module1.submodule1.script3 import *
Is there a way to have script1 always work (no failure when including script3) without changing the import line?
In the end I figured the best way to do what I wanted was to build a wheel.
I need to import that same class into several projects and a wheel enables me to fix bugs only in one convenient location and reimport the de-bugged package on each project.
I actually found a workaround, maybe not the cleanest, but I got inspired by C++ #ifdef guards.
Basically I check the __name__ variable.
if __name__ == "__main__" :
from script1 import scriptObject as scriptObject
elif __name__ == "__main__" :
from module1.script1 import scriptObject as scriptObject
else :
raise Exception(f"__name__ = {__name__} is not a valid guard! Make sure project indentation is correct.")

Django unable to get models module

I am learning Django and not sure what is causing the error 'ModuleNotFoundError: No module named 'models''
even though the files are in the same folder
files are available here
File "/Users/mayanksharma/Library/Mobile Documents/com~apple~CloudDocs/for Stackoverflow/app-7-django/blogs/urls.py", line 1, in <module>
from . import views
File "/Users/mayanksharma/Library/Mobile Documents/com~apple~CloudDocs/for Stackoverflow/app-7-django/blogs/views.py", line 2, in <module>
from models import Post
ModuleNotFoundError: No module named 'models'
Do you mean by?
from .models import Post
Replace from . import views with:
import sys
sys.append('..')
import views
This was something to do with python reading path instead of from .models import Post or from . import views I gave from app.models import Post and that made it work

Python import from parent directory for dockerize structure

I have a project with two applications. They both use a mongo-engine database model file. Also they have to start in different Docker containers, but use the same Mongo database in the fird container. Now my app structure looks like this:
app_root/
app1/
database/
models.py
main.py
app2/
database/
models.py
main.py
And it works fine, BUT I have to support two same files database/models.py. I dont want to do this and I make the next structure:
app_root/
shared/
database/
models.py
app1/
main.py
app2/
main.py
Unfortunately it doesnt work for me, because when I try this in my main.py:
from ..shared.database.models import *
I get
Exception has occurred: ImportError
attempted relative import with no known parent package
And when I try
from app_root.shared.database.models import *
I get
Exception has occurred: ModuleNotFoundError No module named 'app_root'
Please, what do I do wrong?
In the file you perform the import, try adding this:
import os
import sys
sys.path.append(os.path.abspath('../../..'))
from app_root.shared.database.models import *

Import of an attribute of a python module fails

I have the following directory structure:
http://localhost:8888/notebooks/translation.ipynb
http://localhost:8888/edit/Fill_temp/prepare_test_data.py
In
prepare_test_data.py
I have a function:
def to_cap (EXP_FILE, SAMPLES_FILE: str= EXP_FILE + '.cap', cap_rate=0, by_token=False):
In the notebook
translation.ipynb
I do these imports:
%load_ext autoreload
%autoreload 2
import Fill_temp
import Fill_temp.prepare_test_data
then I run
Fill_temp.prepare_test_data.to_cap("en12.json.pres", "en12.cap.0")
and I get
AttributeError: module 'Fill_temp.prepare_test_data' has no attribute 'to_cap'
How come?
I explicitly imported both the Fill_temp package and the prepare_test_data module.
Do I need to import even the lowest level functions that are defined in the module?
EDIT:
I tried to import the low level function explicitly:
%load_ext autoreload
%autoreload 2
import Fill_temp
import Fill_temp.prepare_test_data
import Fill_temp.prepare_test_data.to_cap
but I get:
ModuleNotFoundError: No module named
'Fill_temp.prepare_test_data.to_cap';
'Fill_temp.prepare_test_data' is not a package
So what shall I do?
This is a bit bizarre. Basically, it turned out that there was a syntax error in that low level function.
But instead of saying it jupyter was saying that it doesn't see that function. Which is a really counter-intuitive error message.

Importing all variables from a flexibly defined module

I have a main config.py file and then specific client config files, e.g. client1_config.py.
What I'd like to do is import all variables within my client1_config.py file into my config.py file. The catch is I want to do this flexibly at runtime according to an environment variable. It would look something like this:
import os
import importlib
client = os.environ['CLIENT']
client_config = importlib.import_module(
'{client}_config'.format(
client=client))
from client_config import *
This code snippet returns the following error: ModuleNotFoundError: No module named 'client_config'
Is it possible (and how) to achieve what I'm trying to do or Python does not support this kind of importing at all?
The call to import_module already imports the client configuration. from client_config import * assumes that client_config is the name of the module you are trying to import, just as import os will import the module os even if you create a variable os beforehand:
os = "sys"
import os # still imports the os module, not the sys module
In the following, assume that we have a client1_config.py which just contains one variable:
dummy = True
To add its elements to the main namespace of config.py so that you can access them directly, you can do the following:
import importlib
client = "client1"
# Import the client's configuration
client_config = importlib.import_module(f"{client}_config")
print(client_config.dummy) # True
# Add all elements from client_config
# to the main namespace:
globals().update({v: getattr(client_config, v)
for v in client_config.__dict__
if not v.startswith("_")})
print(dummy) # True
However, I would suggest to access the client's configuration as config.client for clarity and to avoid the client's configuration file overwriting values in the main configuration file.

Resources