Using Numpy from keyword.py - python

I want to use NumPy in a Python script that uses pandas to process an Excel file. However, one of my constraints is that my file must be named keyword.py, which causes an import error. The import error is traced back to a line from keyword import iskeyword as _iskeyword in C:\Python27\lib\collections.py, which I assume causes an error because my own keyword.py is overriding the default keyword module. Is there any way to avoid this collision?

Not pretty, but a keyword.py of
if True:
import imp, sys
keyword_loc = imp.find_module("keyword", sys.path[1:])[1]
imp.load_source("keyword", keyword_loc)
import collections
print(collections.Counter)
fails with an AttributeError if we replace True with False, but gives me
(2.7) dsm#notebook:~/coding/kw$ python keyword.py
<class 'collections.Counter'>
as is. This works by finding out where the original keyword library is and manually importing it. After this, any following attempts to import keyword will see that it's already there.

For working with a single script, you can remove the current directory from the import search path. That might be sufficient for working on your TopCoder problem, but I wouldn't recommend it as a long-term solution. (Long-term: don't use file names that mirror the standard library.)
If the following script is called keyword.py, it can be run and the import of collections will not trigger an error.
# keyword.py
# Remove the current directory from the import search path
# This is a hack, but it will be sufficient for working with a
# single script that doesn't import any other modules from the
# current directory.
import sys
sys.path = sys.path[1:]
import collections
print(collections)

Related

python go up 2 directories gives syntax error

I am making a script (python) and need to import other files (complete).
The file I would like to import, is 2 directories up from the script.
Normal in Python you would do something like
../../../file.py <-- goes up 3 directories
When I do this in Python it gives a syntax error.
..file for example works but as soon as I chain it ../..file.py the syntax error comes in.
I tried
../..file
../../file
/../..file
/../../file
The error says invalid syntax.
The complete command is
from ../..file import *
I would like to import all the content of the file.
The path needs to be relative due to the nature of the script. No hardcoding allowed.
How can I go up multiple directories in Python?
importlib was added to Python 3 to programmatically import a module.
import importlib
moduleName = input('Enter module name:')
importlib.import_module(moduleName)
The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.
If you want to import the whole file you can just do import file. Then you can choose the function that you are interesting in.
for example:
import FULL_PATH_TO_MY_FILE
my_file.my_func...
or you can try:
from FULL_PATH_TO_MY_FILE import *
and then you can use each function in your file like this - myfunc()

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.

How can I import a python module whose name is a uid?

For some reason, I had to change a module name from A.py to 0880ceae-8a46-11eb-bcf6-38f9d349be8e.py. 0880ceae-8a46-11eb-bcf6-38f9d349be8e.py is a uid generated by uuid.uuid1().
After my change, I try to import a class B from the py file by the following two ways, both do not work out.
First solution is to import directly
from 0880ceae-8a46-11eb-bcf6-38f9d349be8e import B
It has an error SyntaxError: invalid token
Second solution is to define a variable before import
uid = '0880ceae-8a46-11eb-bcf6-38f9d349be8e'
from uid import Model_API
And it has en error ModuleNotFoundError: No module named 'uid'
Anyone has a good idea? Thanks.
Here is possible solution to your problem tested using python3:
# Modern approach
import importlib
module = importlib.import_module(".", "0880ceae-8a46-11eb-bcf6-38f9d349be8e")
module.hello()
# Deprecated way
module = __import__("0880ceae-8a46-11eb-bcf6-38f9d349be8e")
module.hello()
Both of the above methods are tested and works.
Here are the rules to keep in mind:
Check your filename should end with .py extension, .py.py will cause ModuleNotFoundError.
Make sure to not include .py extension while using in importlib module.

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 3.5.1 import class in the same directory

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

Categories

Resources