Are slice objects mutable in function declaration? - python

After learning about how default arguments work in python, I went over all my code to look for potential bugs occuring when using mutable sequences.
Now I have a function whose signature is:
def get_measurements(self, shape = slice(None, None, None),
size = slice(None, None, None),
height = slice(None, None, None),
pressure = slice(None, None, None),
LE = slice(None, None, None),
fname = None)
And I'm wondering now, are slice objects mutable? And will this cause a problem in above case with default values?

slice objects are not mutable.
>>> s = slice(None)
>>> s
slice(None, None, None)
>>> s.start = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
>>> s.stop = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
>>> s.step = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute

Related

TypeError: NoneType object is not iterable

When I am iterating through my variable it gives me an error which I show as below.
Traceback (most recent call last):
File "C:\Users\ZHEN YUAN\Desktop\东航第一步\wen2.py", line 13, in <module>
for i in Names:
TypeError: 'NoneType' object is not iterable
Your function wenjian() does not have any return statements, so it will always return None, by default. That's why Names = wenjian(file) assigns the value None to Names, and so you can't iterate over Names with the for loop.
import os
def wenjian(file):
for root,dirs,files in os.walk(file):
for file in files:
filename = os.path.join(root,file)
print (filename[-28:])
file = ("C:\Users\ZHEN YUAN\Desktop\东航try")
Names = wenjian(file)
for i in Names:
print (i[1])
PS C:\Users\ZHEN YUAN> & python "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py"
\Desktop\东航try\C2002455.xlsx
Traceback (most recent call last):
File "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py", line 14, in <module>
for i in Names:
TypeError: 'function' object is not iterable

TypeError: object of type 'int' has no len() when using sop.brute

I use the Python3.6 and I've been confused about this question for a long time..so here is my code.
def fo(x,y):
z=np.sin(x)+0.05*x**2+np.cos(y)+0.05*y**2
if output == True:
print("%8.4f %8.4f %8.4f" % (x,y,z))
return z
import scipy.optimize as sop
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
Here is the error I get:
Traceback (most recent call last):
File "<ipython-input-12-c7886e35ff4b>", line 1, in <module>
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2811, in brute
if len(lrange[k]) < 3:
TypeError: object of type 'int' has no len()
here's another try:
r1=slice(-10,10.1,5)
r2=slice(-10,10.1,5)
sop.brute(fo,r1,r2,finish = None)
and the error:
Traceback (most recent call last):
File "<ipython-input-48-230c07265998>", line 1, in <module>
sop.brute(fo,r1,r2,finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2804, in brute
N = len(ranges)
TypeError: object of type 'slice' has no len()
sop.brute(fo,(r1,r2),finish = None)
TypeError: fo() missing 1 required positional argument: 'y'
I'm new to here and sorry if I ask a stupid question but I cant' work it out T.T thx a lot
def fo(p):
x, y = p
z = np.sin(x)+0.05*x**2+np.sin(y)+0.05*y**2
if output == True:
print('%8.4f %8.4f %8.4f' % (x,y,z))
return z
unpack tuple like in the code

python uiautomator TypeError: 'AutomatorDeviceObject' object is not callable

Above are the uiautomator object viewer screenshots with properties. I am using python package uiautomator installed through pip install uiautomator. I am trying to access the three-dotted settings button through UI automator objects. I have tried using the documentation listed at https://github.com/xiaocong/uiautomator#handler
Here is the code and error:
import uiautomator as uia
d = uia.device() #below all are my attempts
>>> d(resourceId="com.android.camera2:id/three_dots").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle").clickable()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").clcik()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/mode_options_toggle", className="com.android.camera2").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(package="com.android.camera2")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(resourceId="com.android.camera2:id/progress_overlay")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View").child(className="android.widget.LinearLayout", resourceId="com.android.camera2:id/mode_options_toggle")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.view.View").child(className="android.widget.LinearLayout", resourceId="com.android.camera2:id/mode_options_toggle").click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(text="").info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d.info
{u'contentDescription': u'', u'checked': False, u'clickable': False, u'scrollable': False, u'text': u'', u'packageName': u'com.android.camera2', u'selected': False, u'enabled': True, u'bounds': {u'top': 0, u'left': 0, u'right': 1440, u'bottom': 2560}, u'className': u'android.widget.FrameLayout', u'focusable': False, u'focused': False, u'checkable': False, u'resourceName': None, u'longClickable': False, u'visibleBounds': {u'top': 0, u'left': 0, u'right': 1440, u'bottom': 2392}, u'childCount': 2}
>>> d(packageName=u'com.android.camera2).info
File "<stdin>", line 1
d(packageName=u'com.android.camera2).info
^
SyntaxError: EOL while scanning string literal
>>> d(packageName=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'com.android.camera2').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className=u'android.widget.FrameLayout').info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>> d(className="android.widget.FrameLayout").info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'AutomatorDeviceObject' object is not callable
>>>
After all attempts, I am still not able to access the any of the UI objects. Please let me know what am I missing here?
Change:
import uiautomator as uia
d = uia.device()
To:
import uiautomator as uia
d = uia.device
This should solve your problem.
It is happening because you're calling the function device() inside a variable. So "d" is not a function, but use a function to receive a value.
When we call a function using parenthesis Python understands we are calling it and using this result on your variable "d". That's the reason why you're facing "object is not callable", because no object is being passed as parameter to "device()".
When we don't use parenthesis we not call the function, we make a reference to it and the parameters will be passed when we call it.
Hope it helps!
Not a solution to your problem but an alternative: using AndroidViewClient/culebra you can run
culebra -uG -o camera-options.py
once you have the window you can click on the options dots
see the result immediately
and at the same time, the script containing the code to reproduce this action will be generated
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2017 Diego Torres Milano
Created on 2017-11-24 by Culebra v13.5.2
__ __ __ __
/ \ / \ / \ / \
____________________/ __\/ __\/ __\/ __\_____________________________
___________________/ /__/ /__/ /__/ /________________________________
| / \ / \ / \ / \ \___
|/ \_/ \_/ \_/ \ o \
\_____/--<
#author: Diego Torres Milano
#author: Jennifer E. Swofford (ascii art snake)
'''
import re
import sys
import os
try:
sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient
TAG = 'CULEBRA'
_s = 5
_v = '--verbose' in sys.argv
kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
vc = ViewClient(device, serialno, **kwargs2)
#vc.dump(window='-1') # FIXME: seems not needed
vc.dump(window=-1)
vc.findViewWithContentDescriptionOrRaise(u'''Options''').touch()

AttributeError: 'NoneType' object has no attribute 'lower'

I'm trying to call a class method inside the init function of the class. I pass in a string to the function but the error shows that its a none type object.
class UserSettings(object):
"""Value object representing a user's settings."""
def __init__(
self, user_id, email, username=None):
self.user_id = user_id
self.email = email
self.profile_picture_data_url = self.fetch_gravatar(email)
#classmethod
def fetch_gravatar(cls, email):
base_url = "http://www.gravatar.com/avatar/"
avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"
avatar_url += urllib.urlencode({'d':'retro', 's':str(AVATAR_SIZE)})
return avatar_url
Here's the error:
Traceback (most recent call last):
File "/home/travis/build/oppia/oppia/core/domain/user_services_test.py", line 78, in test_invalid_emails
user_services.get_or_create_user('user_id', email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 297, in get_or_create_user
user_settings = _create_user(user_id, email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 284, in _create_user
preferred_language_codes=[feconf.DEFAULT_LANGUAGE_CODE])
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 55, in __init__
self.profile_picture_data_url = self.fetch_gravatar(email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 129, in fetch_gravatar
avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"
AttributeError: 'NoneType' object has no attribute 'lower'
AttributeError: 'NoneType' object has no attribute 'lower'
This tells you that you are attempting to read an attribute named lower on the singleton object None.
Now, you use lower in a method call on email. Therefore, email is None.
You must be calling the method with the value None, or an argument that evaluates to None.
# calling the class method:
>>> UserSettings.fetch_gravatar('a#example.com')
'http://www.gravatar.com/avatar/b418773a2c51fb9777a1648346fa7394?s=16&d=retro'
# create instance, call method:
>>> user_settings = UserSettings(user_id=1, email='jill#example.com')
>>> user_settings.fetch_gravatar('jill#example.com')
'http://www.gravatar.com/avatar/e84a7df193a44f643668b74a2bbfdde6?s=16&d=retro'
# calling with a No arguments gives TypeError
>>> UserSettings.fetch_gravatar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fetch_gravatar() takes exactly 2 arguments (1 given)
# calling with None gives your error:
>>> UserSettings.fetch_gravatar(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in fetch_gravatar
AttributeError: 'NoneType' object has no attribute 'lower'

How to see complete traceback?

I have added an assert(0) in a function to understand the sequence of function calls to this function.
Ex:
def my_func():
...lines of code...
assert(0)
...more lines of code...
The logs show only this:
Traceback (most recent call last):
File "/var/www/folder/file.py", line 273, in my_func
assert(0)
AssertionError
I want to see the complete call trace - Example: first_func -> second_func -> my_func
I tried traceback library but it is showing me the same stacktrace.
Please let me know what I am missing here.
Use traceback module for this. I.e.
>>> import traceback
>>> def my_func():
... my_other_func()
...
>>> def my_other_func():
... my_third()
...
>>> def my_third():
... print "Stack"
... traceback.print_stack()
... print "Extracted"
... print repr(traceback.extract_stack())
...
>>>
>>> my_func()
Stack
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_func
File "<stdin>", line 2, in my_other_func
File "<stdin>", line 3, in my_third
Extracted
[('<stdin>', 1, '<module>', None),
('<stdin>', 2, 'my_func', None),
('<stdin>', 2, 'my_other_func', None),
('<stdin>', 5, 'my_third', None)]
>>>

Categories