Python Relative Path Import from subfolder - python-2.7

first post to SO, so if I'm missing some details, please forgive me.
Is there a way to use relative paths from another subfolder without resorting to modifying sys.path via os? Eventually this will be run from a cgi webserver so I'd rather stay away from any -m arguments to python.exe.
I'm using Python 2.7.3 and have a file/directory structure of the following :
| myprog.py
|
+---functions
| myfunctions.py
| __init__.py
|
\---subfolder
mysub.py
In the root, I have a single .py file, called myprog.py :
#file .\myprog.py
from functions import *
hello("Hi from Main")
In the functions folder I have two files, init.py, myfunctions.py :
#The File: functions\__init__.py :
from myfunctions import *
#The File: functions\myfunctions.py :
def hello(sometext):
print sometext
And finally, in the subfolder, I have :
#The File: subfolder\mysub.py :
from ..functions import *
hello("Hi From mysubprogram")
The myprog.py executes fine (when running python.exe myprog.py from the parent folder), printing "Hi From Main", however, the mysub.py (when executed from the subfolder) keeps putting the error: ValueError: Attempted relative import in non-package
I have tried varying combinations in mysub.py such as from ..functions.myfunctions import * yet none yields the desired result.
I have read a few relevant articles :
using __init__.py
How to import classes defined in __init__.py
http://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories
But just can't figure this out. Oh, and once I get this working, I would like to remove the import *'s wherever possible, however, I'd rather not have to put the full paths to the hello function each time it's called, so any advise there or on cleaning up the init.py (using all or in another manner) would be a bonus.
Thanks Blckknght EDIT, I also found the below :
Relative imports for the billionth time
Which, if what I'm requesting isn't possible, perhaps I'm asking the wrong thing. If this is just outright bad practice, is the right way to accomplish my goal using sys.path or is there something else someone can recommend (like not calling functions from ../folders) ?

I think the issue has to do with how you are running the mysub.py script. Python doesn't tend to do well with scripts in packages, since the main script module is always named __main__ rather than its usual name.
I think you can fix this by running mysub with python -m subfolder.mysub, or by manipulating the __package__ variable in mysub.py (as described by PEP 366). It's not neat, unfortunately.

Related

Multiple Transforms for VSCode Snippet

I've got a few snippets set up and working as I would like to, but I'm having a hard time getting one snippet to work where I believe I will need to have multiple transforms occur?
Essentially I have a TypeScript Interface defined for one of my components.
i.e. IRadioButtonListProps.ts which is inside of an Interfaces folder. The Interfaces folder has a sibling folder named Theme containing an interface named IRadioButtonListTheme.ts
Inside of IRadioButtonListProps I'm trying to stub out the entire interface. The snippet I currently have stubs out the interface like...
import * as React from 'react';
import IRadioButtonListPropsTheme from '../Theme/IRadioButtonListPropsTheme';
export interface IRadioButtonListPropsProps {
...props...
}
export default IRadioButtonListPropsProps;
The import line inside of the snippet is...
"import I${TM_FILENAME_BASE/(.*)\\..+$/$1/}Props from './Interfaces/I${TM_FILENAME_BASE/(.*)\\..+$/$1/}Props';"
What I'm trying to have happen and can't seem to figure out is how to also remove the word "Props". So instead of import IRadioButtonListPropsTheme... I would get import import IRadioButtonListTheme....
At the same time, I want to remove all extensions, including those of the form *.abc.abc ("two" extensions) and *.abc (one simple extension).
Is this possible?
It isn't crystal clear what you what but try:
"import ${TM_FILENAME/((\\w*)Props)*?(\\..*)/$2/}Theme from './Interfaces/${TM_FILENAME/((\\w*)Props)*?(\\..*)/$2/}Theme';"
which results in:
import IRadioButtonListTheme from './Interfaces/IRadioButtonListTheme';
from IRadioButtonListProps.ts
and
import CheckboxListTheme from './Interfaces/CheckboxListTheme';
from CheckboxListProps.test.tsx
[Edit] Here is a simpler version which I think also works:
"import ${TM_FILENAME/(Props)*?(\\..*)//}Theme from './Interfaces/${TM_FILENAME/(Props)*?(\\..*)//}Theme';"
match any "Props", if any, replace with nothing.
match from first \. to end of filename, replace with nothing.

Python programmation project structure with unit testing

I have been programming for a while, but never really got deep into it. Now I'm working in a reasearch center and I need to make my stuff coherent and compatible. My coworkers proposed to me a "Standard" method of organizing my project:
Project
|_ LICENCE.txt
|_ README.txt
|_ code
|_ main.py
|_ __init__.py
|_ tests
|_ context.py
|_ test_main.py
That way they say it will be easier to do unit testing and all.
I have visited tens of websites that do exactly the same thing, so I figured it wouldn,t be that bad: wrong. I have been trying for the whole weekend now to make this work and I feel like I'm just getting colder.
Here is what I have:
IDE image with project structure with context.py open in the window
From what I have read in the past few days, This is the correct method, my problem is, no matter how I write it, the code won't recognize bidon.py, nor the funcitons defined in it.
bidon.py is just a file containing
def add(x, y):
return x+y
def sub(x, y):
return x-y
in context it is not possible to use the function add, but when the test file and the .py are in the same folder, it seems to work...
But why doesn't it work even though I have added the path? I tried (in the context.py):
import code
import code
import bidon
from code import bidion
from code import *
from code import bidon
from bidon import *
from code import bidon
from bidon import add
none of these worked.
It gets worse when I try to use the context.py in a test file.
For example in test_bidon.py, I have
import unittest
from .context import code
class TestBidon(unittest.TestCase):
def test_add(self):
result = add(10, 5)
self.assertEqual(result, 15)
if __name__ == "__main___":
unittest.main()
This creates an error telling me that test_bidon.py is not a package?
Again, I tried multiple combinaisons, none worked. Please help me figure this out! I'm out of options and I don't want to spend another day looking for nothing.
I have found a way to do what I wanted. I made a github of my Basic project architecture as I wanted it. There is still work to do in the setup file, but the master now works.
url: https://github.com/PyMarc2/BasicProjectArchitecture
Basically, I don't know why, but it didn't work well when the setup file was in the test folder. Instead, put the setup file right in the project folder.
(os.path.abspath(os.path.join(os.path.dirname(__file__), testFolderNameSetup)))
That command is what saved me.
Thank you!

python tkinter using variables across files,?

I have been playing with Tkinter in Python 2.7, and just ran across something that SHOULD be a bug, but isn't and the program seems to work OK still.
To make my program more manageable, I have split it into separate .py files.
One file (called globs.py) is a list of global variables in the form
global var_1
global var_2
...
Then I import globs into my other files.
In another file I can set the variable, thus...
import globs
globs.var_1 = "some value"
In a third file I can use it..
import globs
if globs.var_1 == "something":
...
So far, all is as expected, but...
I just found out if the variable is NOT mentioned in the globs.py file at all, the program still seems to work OK.
Is this intended behavior? Any other programming language would give a 'variable not found' error.
If it is intended, why should I even setup any variables in globs.py?
What are the drawbacks?
Thanks, Mark.

Testing a python recipe

I want to run a python recipe I found, but I don't know how as it imports from another one!
For example, I would like to test the code here.
I have downloaded it and also downloaded this one as it uses it.
So how can I test the this code by passing the needed parameter as below?!
>>> G = {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6}}
>>> Dijkstra.Dijkstra(G,'s','v')
I have added the two files in one of the python paths, and imported both but still get error
Could you please give me some advice on simple way to test this code?
You really should put the files in your current directory if you are just testing, instead of putting them in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ as that path is reserved for the Python standard library.
It seems that the second recipe, the Priority Dictionary, needs to be put in a file called priodict.py since the Dijkstra code imports from priodict. So, you should have the following files in your current directory: Dijkstra.py, priodict.py. Then you can just start Python and do import Dijkstra, and it should work.
Also, don't modify the Dijkstra code to remove the import as you apparently did...

Error when trying to load Django custom filters into template

I've inherited a Django application that I need to modify using a custom template filter. I'm absolutely new to Django and am quite mystified by it. I thought I had followed the instructions exactly, and also followed all the advice from other posts on the subject, but I still get an error when I include the following line in my template:
{% load mlgb_custom_filters %}
My directory structure is as follows:
mysite (i.e. the project)
__init__.py
mlgb/ (i.e. the app)
__init__.py
templatetags/
__init__.py
mlgb_custom_filters.py
The code of mlgb_custom_filters.py is as follows:
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='fix_dashes')
#stringfilter
def fix_dashes( value ):
return value.replace( '--', 'DASH' )
if __name__ == "__main__":
testvar = fix_dashes( "ouch -- ow -- I hate django" )
print testvar
As you can see, I've added a 'name = main' section to let me run it in standalone mode, just to check that there are no errors in that particular file, and it's fine when run in standalone mode.
Based on someone else's advice, I've also tried importing it into another file, just to see whether there was an import error, and once again, it was fine if I added this to the end of settings.py (while using the dev server):
try:
import mlgb.templatetags.mlgb_custom_filters
except Exception, exc:
print 'error importing mlgb_custom_filters'
print exc
Also, INSTALLED_APPS in settings.py includes the line 'mysite.mlgb', and I have also tried putting just 'mlgb' instead of 'mysite.mlgb' there, as yet another person suggested. And I restarted the dev server every time I made a change.
I think I have tried every single suggestion that I have found on the web until now. Does anyone have any new ideas? Could it be anything to do with the fact that I have inherited a directory structure where the template directory is not within the same structure as the application, i.e. it is not under mysite? Scraping the barrel for ideas here! I hope someone can help.
OK, in the situation that I was in when first posting this question, it seems all I actually needed to do was touch a wsgi file under my appname/apache directory to force the application to be refreshed. Yesterday's initial answer was a red herring. Basically I should have touched the file myproject/myapp/apache/myapp.wsgi. Then maybe restart Apache for good measure? But the confusion was caused by the fact that apparently it wasn't enough either simply to restart Apache or to manually recompile the Python. In order to pick up my changes, seems like I needed to touch that wsgi file. Then all is well.
I can now post an answer to my own question thanks to the help of my colleague Masud Khokhar, whose brilliant detective work has saved the day. To recap, my application worked fine until I added a 'load' statement to one of my template files, to load a 'custom filters' module. Masud identified that now I needed to use a full/absolute path to the template file in urls.py instead of a relative one as I had before (and which worked before, until it needed to load the custom filters module). So, in urls.py, I had a section of code as follows:
url(r'^book/(?P<object_id>\d+)/$', 'list_detail.object_detail',
kwargs={
'queryset':Book.objects.all(),
'template_name' : 'mlgb/mlgb_detail.html'
},
name='mlgb_detail'
),
Instead of this:
'template_name' : 'mlgb/mlgb_detail.html'
I needed something like this:
'template_name' : '/THE_FULL_PATH/mlgb/templates/mlgb/mlgb_detail.html'
Made that change - sorted! Thank you once again, Masud.