I'm running the simplest possible test problem that is given with the pytzwhere package. The module imports, but I'm getting an error. pytzwhere seems like a good offline option for getting timezones from GPS coordinates, but there isn't much documentation. Any help on how to reconcile this is appreciated!
In [94]:
import tzwhere
w = tzwhere()
print w.tzNameAt(1.352083, 103.819836)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-94-0b50c8083e93> in <module>()
1 import tzwhere
2
----> 3 w = tzwhere()
4 print w.tzNameAt(1.352083, 103.819836)
TypeError: 'module' object is not callable
Edit:
This has been resolved with the following code modification per the comments below -
In [108]:
from tzwhere import tzwhere
w = tzwhere.tzwhere()
print w.tzNameAt(1.352083, 103.819836)
-----------------------------------------------------------------------------
Reading json input file: /Users/user/anaconda/lib/python2.7/site-packages/tzwhere/tz_world_compact.json
Asia/Singapore
You cannot just instantiave w from module like w = tzwhere(). tzwhere is a module containing class tzwhere. As Python correctly noted, module is not callable.
from tzwhere import tzwhere
w = tzwhere()
First line imports class tzwhere from module tzwhere.
Edit: If you do import "my way" :-) w = tzwhere() is valid creation of w as instance of class tzwhere.
Usually in Python, class would be named TzWhere, which would avoid such confusion.
I assume you are trying to use https://github.com/pegler/pytzwhere/blob/master/tzwhere/tzwhere.py
Related
I don't have any files named re or requests in my source code directory.
The function 're.compile()' worked well a few days ago, but suddenly this error happens.
import requests as re
p = re.compile('[a-z]+')
m = p.search("python")
print(m)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7864\2076162965.py in <module>
1 import requests as re
----> 2 p = re.compile('[a-z]+')
3 m = p.search("python")
4 print(m)
AttributeError: module 'requests' has no attribute 'compile'
So i deleted and reinstall requests library and checked how this code works, but same error happens.
I'm tyring to import the "gleam" package in Python 3. I have installed the "gleam" package successfully, but still it showing error.
from wtforms import fields
from ggplot import *
from gleam import Page, panels
class ScatterInput(panels.Inputs):
title = fields.StringField(label="Title of plot:")
yvar = fields.SelectField(label="Y axis",
choices=[("beef", "Beef"),
("pork", "Pork")])
smoother = fields.BooleanField(label="Smoothing Curve")
class ScatterPlot(panels.Plot):
name = "Scatter"
def plot(self, inputs):
p = ggplot(meat, aes(x='date', y=inputs.yvar))
if inputs.smoother:
p = p + stat_smooth(color="blue")
p = p + geom_point() + ggtitle(inputs.title)
return p
class ScatterPage(Page):
input = ScatterInput()
output = ScatterPlot()
ScatterPage.run()
Error:
ModuleNotFoundError - Traceback (most> recent call last) in ()
----> 1 import gleam
C:\pythonNJ\lib\site-packages\gleam__init__.py in ()
5 import os
6 import json
----> 7 import urlparse
8 from collections import namedtuple
9
ModuleNotFoundError: No module named 'urlparse'
I looked for the solution and I found that urlparse has been moved to a new module in python 3, which can be imported as
from urllib.parse import urlparse
And I even imported it, but still when I trying to import "gleam" package it shows error of module "urlparse". Can you suggest me how to bypass it (bypassing import urlparse statement and importing gleam package in Python 3).
I know how to import the urlparse but I don't know how to import the gleam package.
You have two possiblities:
Modify source code yourself as you stated inside gleam package, but it could work incorrectly.
Fall back to version of python it works on - so 2.7 it seems, since the modification you mentioned was done with python 3.0 release. It's stated in docs here.
Just do this to get over it:
from:
import urlparser
to:
import urllib.parse
I am trying import a module in Jupyter and it is not working:
import alyn
ImportError Traceback (most recent call last)
<ipython-input-8-8e9535ea4303> in <module>()
----> 1 import alyn
~\Anaconda3\envs\tracx\lib\site-packages\alyn\__init__.py in <module>()
1 """ Import required modules"""
----> 2 from deskew import *
3 from skew_detect import *
ImportError: No module named 'deskew'
I don't quite understand why, since the package in question has a correct init.py file:
whose contents are:
""" Import required modules"""
from deskew import *
from skew_detect import *
What am I missing?
P.S.
This is all taking place on Windows 10.
Well, I've figured it out!
Turns out that the package I was trying to import is written in Python 2 and its init file is using the relative import mechanism. However, I am working in Python 3 and relative import is no longer supported in it. The init file can be made to work in Python 3 by adding a . in both lines, like this:
""" Import required modules"""
from .deskew import *
from .skew_detect import *
I think this should be backward compatible with Python 2.
I'm using PyYAML, and would like to be able to use a string-concatenating constructor in my .yaml files.
This post shows how to add such constructors to PyYAML:
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
## register the tag handler
yaml.add_constructor('!join', join)
The above works when I enter it in a python terminal. However, I want to put the above in my_package's __init__.py file, so that I can do:
from my_package import yaml # my_package.__init__.py contains the above code
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")
However, this crashes with the message:
AttributeError Traceback (most recent call last)
<ipython-input-1-1107dafdb1d2> in <module>()
----> 1 import simplelearn.yaml
/home/mkg/projects/simplelearn/simplelearn/__init__.py in <module>()
----> 1 import yaml
2
3 def __join(loader, node):
4 '''
5 Concatenates a sequence of strings.
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc in <module>()
AttributeError: 'module' object has no attribute 'add_constructor'
What's going on? Why can't python find yaml.add_constructor?
Your loading the module yaml from the file:
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc
You either named one of your own files yaml.py, or you did have that file
before and renamed it, but forgot to remove the yaml.pyc. So you are not loading the PyYAML interpreter with import yaml.
The easiest way to verify is to include a temporary line after the import:
import yaml
print(yaml.__file__)
you should see something like .../site-packages/yaml/__init__.pyc.
I'm trying to reach 100% testing coverage in a bit of code that I'm writing. The following block of code, however, is giving me trouble.
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^localized_recurrence\.duration_field\.DurationField"])
except ImportError:
pass
The code above is part of my module under test. I need to create a test (without modifying the code above) which follows the ImportError branch.
How can I programmatically cause the ImportError to occur, while only writing code in my tests?
I'd try patching sys.modules and replacing south.modelsinspector with a mock module.
See the docs on Import statement for inspiration.
In [1]: from re import sub
In [2]: import sys
In [3]: sys.modules['re'] = {}
In [4]: from re import sub
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/kos/codility/frontend_v2/<ipython-input-4-6d4794835d43> in <module>()
----> 1 from re import sub
ImportError: cannot import name sub
You can do it in a narrow context by using mock.patch.dict (as a test decorator or context manager):
In [6]: with mock.patch.dict('sys.modules', {'re': {}}):
from re import sub
...:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-6-7479025ab931> in <module>()
1 with mock.patch.dict('sys.modules', {'re': {}}):
----> 2 from re import sub
3
ImportError: cannot import name sub
In [8]: from re import sub
In [9]:
You can change sys.path for the test. For example:
>>>import bs4
>>>
>>>import sys
>>>p=sys.path
>>>sys.path=['']
>>>import bs4
ImportError: No module named bs4
>>>sys.path=p
>>>import bs4
>>>
Just modify sys.path for that specific test on setUp() and later on tearDown() restore it.
Hope this helps!