AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).
The error occurred here:
json.load (jsonofabitch)['data']['children']
Well, you aren’t looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonofabitch, which currently names a string (which you created by calling .read on the response).
Solution: don’t call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .
回答 2
如果收到这样的python错误:
AttributeError:'str' object has no attribute 'some_method'
This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.
class A(object):def salutation(self, accusative):print"hello", accusative
# note this function is intentionally on the module, and not the class abovedef __getattr__(mod, name):return getattr(A(), name)if __name__ =="__main__":# i hope here to have my __getattr__ function above invoked, since# salutation does not exist in the current namespace
salutation("world")
这使:
matt@stanley:~/Desktop$ python getattrmod.py
Traceback(most recent call last):File"getattrmod.py", line 9,in<module>
salutation("world")NameError: name 'salutation'isnot defined
How can implement the equivalent of a __getattr__ on a class, on a module?
Example
When calling a function that does not exist in a module’s statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on the module.
class A(object):
def salutation(self, accusative):
print "hello", accusative
# note this function is intentionally on the module, and not the class above
def __getattr__(mod, name):
return getattr(A(), name)
if __name__ == "__main__":
# i hope here to have my __getattr__ function above invoked, since
# salutation does not exist in the current namespace
salutation("world")
Which gives:
matt@stanley:~/Desktop$ python getattrmod.py
Traceback (most recent call last):
File "getattrmod.py", line 9, in <module>
salutation("world")
NameError: name 'salutation' is not defined
Recently some historical features have made a comeback, the module __getattr__ among them, and so the existing hack (a module replacing itself with a class in sys.modules at import time) should be no longer necessary.
In Python 3.7+, you just use the one obvious way. To customize attribute access on a module, define a __getattr__ function at the module level which should accept one argument (name of attribute), and return the computed value or raise an AttributeError:
This will also allow hooks into “from” imports, i.e. you can return dynamically generated objects for statements such as from my_module import whatever.
On a related note, along with the module getattr you may also define a __dir__ function at module level to respond to dir(my_module). See PEP 562 for details.
回答 1
您在这里遇到两个基本问题:
__xxx__ 方法只在类上查找
TypeError: can't set attributes of built-in/extension type 'module'
There are two basic problems you are running into here:
__xxx__ methods are only looked up on the class
TypeError: can't set attributes of built-in/extension type 'module'
(1) means any solution would have to also keep track of which module was being examined, otherwise every module would then have the instance-substitution behavior; and (2) means that (1) isn’t even possible… at least not directly.
Fortunately, sys.modules is not picky about what goes there so a wrapper will work, but only for module access (i.e. import somemodule; somemodule.salutation('world'); for same-module access you pretty much have to yank the methods from the substitution class and add them to globals() eiher with a custom method on the class (I like using .export()) or with a generic function (such as those already listed as answers). One thing to keep in mind: if the wrapper is creating a new instance each time, and the globals solution is not, you end up with subtly different behavior. Oh, and you don’t get to use both at the same time — it’s one or the other.
There is actually a hack that is occasionally used and recommended: a
module can define a class with the desired functionality, and then at
the end, replace itself in sys.modules with an instance of that class
(or with the class, if you insist, but that’s generally less useful).
E.g.:
This works because the import machinery is actively enabling this
hack, and as its final step pulls the actual module out of
sys.modules, after loading it. (This is no accident. The hack was
proposed long ago and we decided we liked enough to support it in the
import machinery.)
So the established way to accomplish what you want is to create a single class in your module, and as the last act of the module replace sys.modules[__name__] with an instance of your class — and now you can play with __getattr__/__setattr__/__getattribute__ as needed.
Note 1: If you use this functionality then anything else in the module, such as globals, other functions, etc., will be lost when the sys.modules assignment is made — so make sure everything needed is inside the replacement class.
Note 2: To support from module import * you must have __all__ defined in the class; for example:
class A(object):
....
# The implicit global instance
a= A()
def salutation( *arg, **kw ):
a.salutation( *arg, **kw )
Why? So that the implicit global instance is visible.
For examples, look at the random module, which creates an implicit global instance to slightly simplify the use cases where you want a “simple” random number generator.
Similar to what @Håvard S proposed, in a case where I needed to implement some magic on a module (like __getattr__), I would define a new class that inherits from types.ModuleType and put that in sys.modules (probably replacing the module where my custom ModuleType was defined).
See the main __init__.py file of Werkzeug for a fairly robust implementation of this.
回答 5
这有点黑,但是…
import types
class A(object):def salutation(self, accusative):print"hello", accusative
def farewell(self, greeting, accusative):print greeting, accusative
defAddGlobalAttribute(classname, methodname):print"Adding "+ classname +"."+ methodname +"()"def genericFunction(*args):return globals()[classname]().__getattribute__(methodname)(*args)
globals()[methodname]= genericFunction
# set up the global namespace
x =0# X and Y are here to add them implicitly to globals, so
y =0# globals does not change as we iterate over it.
toAdd =[]def isCallableMethod(classname, methodname):
someclass = globals()[classname]()
something = someclass.__getattribute__(methodname)return callable(something)for x in globals():print"Looking at", x
if isinstance(globals()[x],(types.ClassType, type)):print"Found Class:", x
for y in dir(globals()[x]):if y.find("__")==-1:# hack to ignore default methodsif isCallableMethod(x,y):if y notin globals():# don't override existing global names
toAdd.append((x,y))for x in toAdd:AddGlobalAttribute(*x)if __name__ =="__main__":
salutation("world")
farewell("goodbye","world")
import types
class A(object):
def salutation(self, accusative):
print "hello", accusative
def farewell(self, greeting, accusative):
print greeting, accusative
def AddGlobalAttribute(classname, methodname):
print "Adding " + classname + "." + methodname + "()"
def genericFunction(*args):
return globals()[classname]().__getattribute__(methodname)(*args)
globals()[methodname] = genericFunction
# set up the global namespace
x = 0 # X and Y are here to add them implicitly to globals, so
y = 0 # globals does not change as we iterate over it.
toAdd = []
def isCallableMethod(classname, methodname):
someclass = globals()[classname]()
something = someclass.__getattribute__(methodname)
return callable(something)
for x in globals():
print "Looking at", x
if isinstance(globals()[x], (types.ClassType, type)):
print "Found Class:", x
for y in dir(globals()[x]):
if y.find("__") == -1: # hack to ignore default methods
if isCallableMethod(x,y):
if y not in globals(): # don't override existing global names
toAdd.append((x,y))
for x in toAdd:
AddGlobalAttribute(*x)
if __name__ == "__main__":
salutation("world")
farewell("goodbye", "world")
This works by iterating over the all the objects in the global namespace. If the item is a class, it iterates over the class attributes. If the attribute is callable it adds it to the global namespace as a function.
It ignore all attributes which contain “__”.
I wouldn’t use this in production code, but it should get you started.
Here’s my own humble contribution — a slight embellishment of @Håvard S’s highly rated answer, but a bit more explicit (so it might be acceptable to @S.Lott, even though probably not good enough for the OP):
Create your module file that has your classes. Import the module. Run getattr on the module you just imported. You can do a dynamic import using __import__ and pull the module from sys.modules.
AttributeError: module 'enum' has no attribute 'IntFlag'
$ /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
Failed to import the site module
Traceback(most recent call last):File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 544,in<module>
main()File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 530,in main
known_paths = addusersitepackages(known_paths)File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 282,in addusersitepackages
user_site = getusersitepackages()File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 258,in getusersitepackages
user_base = getuserbase()# this will also set USER_BASE File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 248,in getuserbase
USER_BASE = get_config_var('userbase')File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 601,in get_config_var
return get_config_vars().get(name)File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 580,in get_config_vars
import _osx_support
File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_osx_support.py", line 4,in<module>import re
File"/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 142,in<module>classRegexFlag(enum.IntFlag):AttributeError: module 'enum' has no attribute 'IntFlag'
When I attempt to run the Console(or run anything with Python3), this error is thrown:
AttributeError: module 'enum' has no attribute 'IntFlag'
$ /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
Failed to import the site module
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 544, in <module>
main()
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 530, in main
known_paths = addusersitepackages(known_paths)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 282, in addusersitepackages
user_site = getusersitepackages()
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 258, in getusersitepackages
user_base = getuserbase() # this will also set USER_BASE
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 248, in getuserbase
USER_BASE = get_config_var('userbase')
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 601, in get_config_var
return get_config_vars().get(name)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 580, in get_config_vars
import _osx_support
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_osx_support.py", line 4, in <module>
import re
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 142, in <module>
class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
The class IntFlag exists within enum.py. So, why is the AttributeError being thrown?
It’s because your enum is not the standard library enum module. You probably have the package enum34 installed.
One way check if this is the case is to inspect the property enum.__file__
import enum
print(enum.__file__)
# standard library location should be something like
# /usr/local/lib/python3.6/enum.py
Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.
pip uninstall -y enum34
If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.
For me this error occured after installing of gcloud component app-engine-python in order to integrate into pycharm. Uninstalling the module helped, even if pycharm is now not uploading to app-engine.
If anyone coming here because of getting this error while running a google app engine Python 3.7 standard environment project in PyCharm then all you need to do is
Make sure the configuration to run is for Flask, not Google App Engine configuration.
Then disable Google App Engine support under Preferences >> Languages & Framework >> Google App Engine
The overall goal is that your app should be fully portable and run in any standard Python environment. You write a standard Python app, not an App Engine Python app. As part of this shift, you are no longer required to use proprietary App Engine APIs and services for your app’s core functionality. At this time, App Engine APIs are not available in the Python 3.7 runtime.
I guess when we create a python 3.7 project in PyCharm as a Google app engine project it still tries to do the same way it does for a python2.7 app
Håken Lid’s answer helped solved my problem (thanks!) , in my case present in Python3.7 running Flask in a Docker container (FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7).
In my case, enum34 was being installed by another library (pip install smartsheet-python-sdk).
For those coming with a similar Docker container problem, here is my final Dockerfile (stripped to the relevant lines):
FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7
...
RUN pip install -r requirements.txt
RUN pip uninstall -y enum34
...
AttributeError: module ‘enum’ has no attribute ‘IntFlag’
simply first i run the command:
unset PYTHONPATH
and then run my desired command then got success in that.
回答 9
使用pip install <required-library> --ignore-installed enum34
安装所需的库后,在构建过程中查找警告。我收到这样的错误: Using legacy setup.py install for future, since package 'wheel' is not installed ERROR: pyejabberd 0.2.11 has requirement enum34==1.1.2, but you'll have enum34 1.1.10 which is incompatible.
I did by using pip install <required-library> --ignore-installed enum34
Once your required library is installed, look for warnings during the build.
I got an Error like this: Using legacy setup.py install for future, since package 'wheel' is not installed ERROR: pyejabberd 0.2.11 has requirement enum34==1.1.2, but you'll have enum34 1.1.10 which is incompatible.
To fix this issue now run the command: pip freeze | grep enum34. This will give you the version of the installed enum34. Now uninstall it by pip uninstall enum34 and reinstall the required version as pip install "enum34==1.1.20"
I have Python 2 and Python 3 installed on my computer. For some strange reason I have in the sys.path of Python 3 also a path to the sitepackage library directory of Python2 when the re module is called. If I run Python 3 and import enum and print(enum.__file__) the system does not show this Python 2 path to site-packages. So a very rough and dirty hack is, to directly modify the module in which enum is imported (follow the traceback paths) and insert the following code just before importing enum:
import sys
for i, p in enumerate(sys.path):
if "python27" in p.lower() or "python2.7" in p.lower(): sys.path.pop(i)
import enum
I was able to fix this by adding enum34 = “==1.1.8” to pyproject.toml.
Apparently enum34 had a feature in v1.1.8 that avoided this error, but
this regressed in v1.1.9+. This is just a workaround though. The
better solution would be for packages to use environment markers so
you don’t have to install enum34 at all unless needed.
Even I had this issue while running python -m grpc_tools.protoc –version
Had to set the PYTHONPATH till site-packages and shutdown all the command prompt windows and it worked. Hope it helps for gRPC users.
Traceback(most recent call last):File"/usr/lib/python2.7/runpy.py", line 174,in _run_module_as_main
"__main__", fname, loader, pkg_name)File"/usr/lib/python2.7/runpy.py", line 72,in _run_code
exec code in run_globals
File"/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel_launcher.py", line 15,in<module>from ipykernel import kernelapp as app
File"/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/__init__.py", line 2,in<module>from.connect import*File"/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/connect.py", line 13,in<module>fromIPython.core.profiledir importProfileDirFile"/home/hu-mka/.local/lib/python2.7/site-packages/IPython/__init__.py", line 48,in<module>from.core.application importApplicationFile"/home/hu-mka/.local/lib/python2.7/site-packages/IPython/core/application.py", line 23,in<module>from traitlets.config.application importApplication, catch_config_error
File"/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/__init__.py", line 1,in<module>from.traitlets import*File"/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 49,in<module>import enum
ImportError:No module named enum
I had this problem in ubuntu20.04 in jupyterlab in my virtual env kernel with python3.8 and tensorflow 2.2.0. Error message was
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/__init__.py", line 2, in <module>
from .connect import *
File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/__init__.py", line 48, in <module>
from .core.application import Application
File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/core/application.py", line 23, in <module>
from traitlets.config.application import Application, catch_config_error
File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/__init__.py", line 1, in <module>
from .traitlets import *
File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 49, in <module>
import enum
ImportError: No module named enum
problem was that in symbolic link in /usr/bin/python was pointing to python2. Solution:
cd /usr/bin/
sudo ln -sf python3 python
Hopefully Python 2 usage will drop off completely soon.
If anyone is having this problem when trying to run Jupyter kernel from a virtualenv, just add correct PYTHONPATH to kernel.json of your virtualenv kernel (Python 3 in example):
You have mutual top-level imports, which is almost always a bad idea.
If you really must have mutual imports in Python, the way to do it is to import them within a function:
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
Now a.py can safely do import b without causing problems.
(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it’s a quick operation.)
I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.
The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first – in this case python ends up initializing module a before b and b.hi() doesn’t exist yet when you try to access it in a.
回答 3
我通过引用以错误方式导入的枚举而收到此错误,例如:
from package importMyEnumClass# ...# in some method:returnMyEnumClass.Member
I experienced this error because the module was not actually imported. The code looked like this:
import a.b, a.c
# ...
something(a.b)
something(a.c)
something(a.d) # My addition, which failed.
The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.
回答 5
我遇到了同样的问题。使用修复reload。
import the_module_name
from importlib import reload
reload(the_module_name)
I ran into this problem when I checked out an older version of a repository from git. Git replaced my .py files, but left the untracked .pyc files. Since the .py files and .pyc files were out of sync, the import command in a .py file could not find the corresponding module in the .pyc files.
The solution was simply to delete the .pyc files, and let them be automatically regenerated.
All the above answers are great, but I’d like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.
Not sure how but the below change sorted my issue:
i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .
Circular imports cause problems, but Python has ways to mitigate it built-in.
The problem is when you run python a.py, it runs a.py but not mark it imported as a module. So in turn a.py -> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi(), it can’t find anything.
Note that the b.hi() that got executed is during a.py -> module b -> module a, not in a.py directly.
In your specific example, you can just run python -c 'import a' at top-level, so the first execution of a.py is registered as importing a module.
回答 11
该订单进口的就是为什么我有问题的原因:
a.py:
############# this is a problem# move this to below#############from b importNewThingclassProblemThing(object):passclass A(object):################ add it here# from b import NewThing###############
nt =NewThing()pass
b.py:
from a importProblemThingclassNewThing(ProblemThing):pass
The order of the importing was the reason why I was having issues:
a.py:
############
# this is a problem
# move this to below
#############
from b import NewThing
class ProblemThing(object):
pass
class A(object):
###############
# add it here
# from b import NewThing
###############
nt = NewThing()
pass
b.py:
from a import ProblemThing
class NewThing(ProblemThing):
pass
Just another example of how it might look, similar to RichieHindie’s answer, but with classes.
回答 12
我已经多次遇到这个问题,但是我并没有尝试更深入地研究它。现在我了解了主要问题。
这次我的问题是从不同的模块(例如以下)中导入序列化器(django和restframework):
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
# the line below was the problem 'srlzprod'from products import serializers as srlzprod
我遇到这样的问题:
from product import serializers as srlzprod
ModuleNotFoundError:No module named 'product'
我要完成的工作如下:
classCampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()# the nested relation of the line below
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
因此,正如上面几行提到的解决方法(顶级导入)所述,我继续进行以下更改:
# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)# by
product = serializers.SerializerMethodField()# and create the following method and call from there the required serializer classdef get_product(self, obj):from products import serializers as srlzprod
p_fields =['id','name',]return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,).data
因此,django runserver的执行没有问题:
./project/settings/manage.py runserver 0:8002--settings=settings_development_mlazo
Performing system checks...System check identified no issues (0 silenced).April25,2020-13:31:56Django version 2.0.7, using settings 'settings_development_mlazo'Starting development server at http://0:8002/Quit the server with CONTROL-C.
代码行的最终状态如下:
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
classCampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
product = serializers.SerializerMethodField()classMeta:
model = mdlpri.CampaignsProducts
fields ='__all__'def get_product(self, obj):from products import serializers as srlzprod
p_fields =['id','name',]return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,).data
I have crossed with this issue many times, but I didnt try to dig deeper about it. Now I understand the main issue.
This time my problem was importing Serializers ( django and restframework ) from different modules such as the following :
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
# the line below was the problem 'srlzprod'
from products import serializers as srlzprod
I was getting a problem like this :
from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'
What I wanted to accomplished was the following :
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
# the nested relation of the line below
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
So, as mentioned by the lines above how to solve it ( top-level import ), I proceed to do the following changes :
# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by
product = serializers.SerializerMethodField()
# and create the following method and call from there the required serializer class
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
Therefore, django runserver was executed without problems :
./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...
System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.
Final state of the code lines was the following :
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
product = serializers.SerializerMethodField()
class Meta:
model = mdlpri.CampaignsProducts
fields = '__all__'
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
AttributeError: 'NoneType' object has no attribute 'something'
The code I have is too long to post here. What general scenarios would cause this AttributeError, what is NoneType supposed to mean and how can I narrow down what’s going on?
NoneType means that instead of an instance of whatever Class or Object you think you’re working with, you’ve actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.
Others have explained what NoneType is and a common way of ending up with it (i.e., failure to return a value from a function).
Another common reason you have None where you don’t expect it is assignment of an in-place operation on a mutable object. For example:
mylist = mylist.sort()
The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you’ve just assigned None to mylist. If you next try to do, say, mylist.append(1) Python will give you this error.
x1 =Noneprint(x1.something)#or
x1 =None
x1.someother ="Hellow world"#or
x1 =None
x1.some_func()# you can avoid some of these error by adding this kind of checkif(x1 isnotNone):...Do something here
else:print("X1 variable is Null or None")
It means the object you are trying to access None. None is a Null variable in python.
This type of error is occure de to your code is something like this.
x1 = None
print(x1.something)
#or
x1 = None
x1.someother = "Hellow world"
#or
x1 = None
x1.some_func()
# you can avoid some of these error by adding this kind of check
if(x1 is not None):
... Do something here
else:
print("X1 variable is Null or None")
g.d.d.c. is right, but adding a very frequent example:
You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it’s not NoneType.
回答 7
建立估算器(sklearn)时,如果忘记在fit函数中返回self,则会得到相同的错误。
classImputeLags(BaseEstimator,TransformerMixin):def __init__(self, columns):
self.columns = columns
def fit(self, x, y=None):""" do something """def transfrom(self, x):return x