Querying a shading node Maya Python - python

I am currently having a problem where i want to query the 'inputX' of a multiplyDivide Node in maya and put the queried number into the 'inputX' of another multiplyDivide node.
The script currently makes an stretchy IK set up for an arm. Using a distanceBetween the shoulder and the wrist (at a certain point, which is what i want to query) the bones would then stretch. So obviously, I don't want to connect the two together.
def stretchyIK(firstJointStore, lastJointStore, side, limb):
GlobalMoveRig = cmds.rename ('GlobalMove_Grp_01')
locFirstJoint = cmds.spaceLocator (n='Loc_' + firstJointStore + '_0#')
locLastJoint = cmds.spaceLocator (n='Loc_' + lastJointStore + '_0#')
pointLoc1 = cmds.pointConstraint (side + '_Fk_' + firstJointStore + suffix, locFirstJoint)
pointLoc2 = cmds.pointConstraint (side + '_Fk_' + lastJointStore + suffix, locLastJoint)
cmds.delete (pointLoc1, pointLoc2)
cmds.pointConstraint (side + '_FK_' + firstJointStore + suffix, locFirstJoint)
cmds.pointConstraint (ikCtr, locLastJoint)
cmds.parent (locFirstJoint, locLastJoint, 'Do_Not_Touch')
#Creating Nodes for Stretchy IK
IkStretch_DisNode = cmds.shadingNode ('distanceBetween', asUtility=True, n='DistBet_IkStretch_' + side + limb + '_#')
cmds.connectAttr (locFirstJoint[0] + '.translate', IkStretch_DisNode + '.point1')
cmds.connectAttr (locLastJoint[0] + '.translate', IkStretch_DisNode + '.point2')
IkStretch_DivNode = cmds.shadingNode ('multiplyDivide', asUtility=True, n='Div_IkStretch_' + side + limb + '_#')
cmds.setAttr (IkStretch_DivNode + '.operation', 2)
input = cmds.connectAttr (IkStretch_DisNode + '.distance', IkStretch_DivNode + '.input1.input1X') ########HELP NEEDED HERE
cmds.setAttr (ikCtr + '.translateX', 2)
IkStretch_MultNode = cmds.shadingNode ('multiplyDivide', asUtility=True, n='Mult_IkStretch_' + side + limb + '_#')
cmds.setAttr (IkStretch_MultNode + '.input1X', IkStretch_DivNode + '.input1.input1X')#WAIT FOR PAUL
cmds.connectAttr (GlobalMoveRig + '.scaleY', IkStretch_MultNode + '.input2X')
cmds.connectAttr (IkStretch_MultNode + '.outputX', IkStretch_DivNode + '.input2X')
IkStretch_Cond_Equ = cmds.shadingNode ('condition', asUtility=True, n='Cond_Equ_IkStretch_' + side + limb + '_#')
IkStretch_Cond_GrtEqu = cmds.shadingNode ('condition', asUtility=True, n='Cond_GrtEqu_IkStretch_' + side + limb + '_#')
cmds.setAttr (IkStretch_Cond_GrtEqu + '.operation', 3)
cmds.connectAttr (ikCtr + '.Enable', IkStretch_Cond_Equ + '.firstTerm')
cmds.setAttr (IkStretch_Cond_Equ + '.secondTerm', 1)
cmds.connectAttr (IkStretch_DisNode + '.distance', IkStretch_Cond_GrtEqu + '.firstTerm')
cmds.connectAttr (IkStretch_MultNode + '.outputX', IkStretch_Cond_GrtEqu + '.secondTerm')
cmds.connectAttr (IkStretch_DivNode + '.outputX', IkStretch_Cond_GrtEqu + '.colorIfTrueR')
cmds.connectAttr (IkStretch_Cond_GrtEqu + '.outColorR', IkStretch_Cond_Equ + '.colorIfTrueR')
cmds.connectAttr (IkStretch_Cond_GrtEqu + '.outColorR', side + '_Ik_' + secondJointStore + suffix + '.scaleX')
cmds.connectAttr (IkStretch_Cond_GrtEqu + '.outColorR', side + '_Ik_' + firstJointStore + suffix + '.scaleX')

Yes, your error makes perfect sense... The attribute you're looking for is actually just '.input1X' rather than '.input1.input1X'.
I know, that isn't very clear, but you'll know in the future. An easy way of figuring out stuff like this, by the way, is manually connecting stuff in Maya and seeing the MEL output in the script editor. You'll get the real deal every time, and translating that stuff to Python afterwards is quick.
So:
cmds.connectAttr(IkStretch_DisNode + '.distance', IkStretch_DivNode + '.input1X')
By the way, I'm not sure why you were assigning the result to input. I admit I'm not sure what that would return, but I don't see how it could be any useful!
Additionally: To answer your direct question, you can use getattr to query the value.
cmds.setAttr(
IkStretch_MultNode + '.input1X',
cmds.getattr(IkStretch_DivNode + '.input1X')
)

In my case, the variable being assigned to be set as the new attribute value was not being evaluated properly. setAttr interpreted the variable value as text, even though the value was input as a float value.
So, I simply assigned the variable and set it to float the variable within the command. In my case, I did the following:
cmds.setAttr(Node + '.input1X', float(variable))

Related

Facing "attribute error:'dict' object has no attribute 'dtype' " in google colab

I have tried "Data Augmentation" for a numeric datatset. Augmentation is successful but while exporting the augmented dataset from google colab I am facing the Attribute Error:'dict' object has no attribute 'dtype'
The part of the code and the error message is given below:
A=[]
A.append(df)
for _ in range(5):
for _,row in df.iterrows():
temp = {
'PERCENT_PUB_DATA': row['PERCENT_PUB_DATA'] + np.random.uniform(percst),
'ACCESS_TO_PUB_DATA':row['ACCESS_TO_PUB_DATA'] + np.random.uniform(accest),
'COUPLING_BETWEEN_OBJECTS':row['COUPLING_BETWEEN_OBJECTS'] + np.random.uniform(coupst),
'DEPTH':row['DEPTH'] + np.random.uniform(deptst),
'LACK_OF_COHESION_OF_METHODS':row['LACK_OF_COHESION_OF_METHODS'] + np.random.uniform(lackst),
'NUM_OF_CHILDREN':row['NUM_OF_CHILDREN'] + np.random.uniform(numost),
'DEP_ON_CHILD':row['DEP_ON_CHILD'] + np.random.uniform(depost),
'FAN_IN':row['FAN_IN'] + np.random.uniform(fanist),
'RESPONSE_FOR_CLASS':row['RESPONSE_FOR_CLASS'] + np.random.uniform(respst),
'WEIGHTED_METHODS_PER_CLASS':row['WEIGHTED_METHODS_PER_CLASS'] + np.random.uniform(weigst),
'minLOC_BLANK':row['minLOC_BLANK'] + np.random.uniform(blankst),
'minBRANCH_COUNT':row['minBRANCH_COUNT'] + np.random.uniform(branchst),
'minLOC_CODE_AND_COMMENT':row['minLOC_CODE_AND_COMMENT'] + np.random.uniform(codest),
'minLOC_COMMENTS':row['minLOC_COMMENTS'] + np.random.uniform(comentsst),
'minCYCLOMATIC_COMPLEXITY':row['minCYCLOMATIC_COMPLEXITY'] + np.random.uniform(cyclost),
'minDESIGN_COMPLEXITY':row['minDESIGN_COMPLEXITY'] + np.random.uniform(desist),
'minESSENTIAL_COMPLEXITY':row['minESSENTIAL_COMPLEXITY'] + np.random.uniform(essest),
'minLOC_EXECUTABLE':row['minLOC_EXECUTABLE'] + np.random.uniform(execst),
'minHALSTEAD_CONTENT':row['minHALSTEAD_CONTENT'] + np.random.uniform(contst),
'minHALSTEAD_DIFFICULTY':row['minHALSTEAD_DIFFICULTY'] + np.random.uniform(diffest),
'minHALSTEAD_EFFORT':row['minHALSTEAD_EFFORT'] + np.random.uniform(effortsst),
'minHALSTEAD_ERROR_EST':row['minHALSTEAD_ERROR_EST'] + np.random.uniform(errost),
'minHALSTEAD_LENGTH':row['minHALSTEAD_LENGTH'] + np.random.uniform(lengtst),
'minHALSTEAD_LEVEL':row['minHALSTEAD_LEVEL'] + np.random.uniform(levst),
'minHALSTEAD_PROG_TIME':row['minHALSTEAD_PROG_TIME'] + np.random.uniform(progst),
'minHALSTEAD_VOLUME':row['minHALSTEAD_VOLUME'] + np.random.uniform(volust),
'minNUM_OPERANDS':row['minNUM_OPERANDS'] + np.random.uniform(operanst),
'minNUM_OPERATORS':row['minNUM_OPERATORS'] + np.random.uniform(operatst),
'minNUM_UNIQUE_OPERANDS':row['minNUM_UNIQUE_OPERANDS'] + np.random.uniform(uoperandst),
'minNUM_UNIQUE_OPERATORS' :row['minNUM_UNIQUE_OPERATORS'] + np.random.uniform(uoperatorst),
'minLOC_TOTAL' :row['minLOC_TOTAL'] + np.random.uniform(totst),
'maxLOC_BLANK' :row['maxLOC_BLANK'] + np.random.uniform(mblankst),
'maxBRANCH_COUNT' :row['maxBRANCH_COUNT'] + np.random.uniform(branchcountst),
'maxLOC_CODE_AND_COMMENT' :row['maxLOC_CODE_AND_COMMENT'] + np.random.uniform(mcodest),
'maxLOC_COMMENTS' :row['maxLOC_COMMENTS'] + np.random.uniform(mcommentst),
'maxCYCLOMATIC_COMPLEXITY' :row['maxCYCLOMATIC_COMPLEXITY'] + np.random.uniform(mcyclost),
'maxDESIGN_COMPLEXITY' :row['maxDESIGN_COMPLEXITY'] + np.random.uniform(mdesist),
'maxESSENTIAL_COMPLEXITY' :row['maxESSENTIAL_COMPLEXITY'] + np.random.uniform(messenst),
'maxLOC_EXECUTABLE' :row['maxLOC_EXECUTABLE'] + np.random.uniform(mlocst),
'maxHALSTEAD_CONTENT' :row['maxHALSTEAD_CONTENT'] + np.random.uniform(mhalconst),
'maxHALSTEAD_DIFFICULTY' :row['maxHALSTEAD_DIFFICULTY'] + np.random.uniform(mhaldiffst),
'maxHALSTEAD_EFFORT' :row['maxHALSTEAD_EFFORT'] + np.random.uniform(mhaleffst),
'maxHALSTEAD_ERROR_EST' :row['maxHALSTEAD_ERROR_EST'] + np.random.uniform(mhalerrst),
'maxHALSTEAD_LENGTH' :row['maxHALSTEAD_LENGTH'] + np.random.uniform(mhallenst),
'maxHALSTEAD_LEVEL' :row['maxHALSTEAD_LEVEL'] + np.random.uniform(mhallevst),
'maxHALSTEAD_PROG_TIME' :row['maxHALSTEAD_PROG_TIME'] + np.random.uniform(mhalpst),
'maxHALSTEAD_VOLUME' :row['maxHALSTEAD_VOLUME'] + np.random.uniform(mhalvst),
'maxNUM_OPERANDS' :row['maxNUM_OPERANDS'] + np.random.uniform(mnumopst),
'maxNUM_OPERATORS' :row['maxNUM_OPERATORS'] + np.random.uniform(mnopst),
'maxNUM_UNIQUE_OPERANDS':row['maxNUM_UNIQUE_OPERANDS'] + np.random.uniform(muopst),
'maxNUM_UNIQUE_OPERATORS':row['maxNUM_UNIQUE_OPERATORS'] + np.random.uniform(muoprst),
'maxLOC_TOTAL':row['maxLOC_TOTAL'] + np.random.uniform(mloctst),
'avgLOC_BLANK' :row['avgLOC_BLANK'] + np.random.uniform(alocbst),
'avgBRANCH_COUNT' :row['avgBRANCH_COUNT'] + np.random.uniform(abcst),
'avgLOC_CODE_AND_COMMENT' :row['avgLOC_CODE_AND_COMMENT'] + np.random.uniform(aloccodest),
'avgLOC_COMMENTS' :row['avgLOC_COMMENTS'] + np.random.uniform(aloccommst),
'avgCYCLOMATIC_COMPLEXITY' :row['avgCYCLOMATIC_COMPLEXITY'] + np.random.uniform(acyclost),
'avgDESIGN_COMPLEXITY' :row['avgDESIGN_COMPLEXITY'] + np.random.uniform(adesigst),
'avgESSENTIAL_COMPLEXITY' :row['avgESSENTIAL_COMPLEXITY'] + np.random.uniform(aessest),
'avgLOC_EXECUTABLE' :row['avgLOC_EXECUTABLE'] + np.random.uniform(alocexest),
'avgHALSTEAD_CONTENT' :row['avgHALSTEAD_CONTENT'] + np.random.uniform(ahalconst),
'avgHALSTEAD_DIFFICULTY' :row['avgHALSTEAD_DIFFICULTY'] + np.random.uniform(ahaldifficst),
'avgHALSTEAD_EFFORT' :row['avgHALSTEAD_EFFORT'] + np.random.uniform(ahaleffortst),
'avgHALSTEAD_ERROR_EST' :row['avgHALSTEAD_ERROR_EST'] + np.random.uniform(ahalestst),
'avgHALSTEAD_LENGTH' :row['avgHALSTEAD_LENGTH'] + np.random.uniform(ahallenst),
'avgHALSTEAD_LEVEL' :row['avgHALSTEAD_LEVEL'] + np.random.uniform(ahallevst),
'avgHALSTEAD_PROG_TIME' :row['avgHALSTEAD_PROG_TIME'] + np.random.uniform(ahalprogst),
'avgHALSTEAD_VOLUME' :row['avgHALSTEAD_VOLUME'] + np.random.uniform(ahalvolst),
'avgNUM_OPERANDS' :row['avgNUM_OPERANDS'] + np.random.uniform(ahalnumost),
'avgNUM_OPERATORS' :row['avgNUM_OPERATORS'] + np.random.uniform(ahalnumopst),
'avgNUM_UNIQUE_OPERANDS' :row['avgNUM_UNIQUE_OPERANDS'] + np.random.uniform(anumoperanst),
'avgNUM_UNIQUE_OPERATORS' :row['avgNUM_UNIQUE_OPERATORS'] + np.random.uniform(anumuniquest),
'avgLOC_TOTAL' :row['avgLOC_TOTAL'] + np.random.uniform(aloctst),
'sumLOC_BLANK' :row['sumLOC_BLANK'] + np.random.uniform(alocbst),
'sumBRANCH_COUNT' :row['sumBRANCH_COUNT'] + np.random.uniform(sumbst),
'sumLOC_CODE_AND_COMMENT' :row['sumLOC_CODE_AND_COMMENT'] + np.random.uniform(sunlst),
'sumLOC_COMMENTS' :row['sumLOC_COMMENTS'] + np.random.uniform(sumlcommst),
'sumCYCLOMATIC_COMPLEXITY' :row['sumCYCLOMATIC_COMPLEXITY'] + np.random.uniform(sumcyclost),
'sumDESIGN_COMPLEXITY' :row['sumDESIGN_COMPLEXITY'] + np.random.uniform(sumdesist),
'sumESSENTIAL_COMPLEXITY' :row['sumESSENTIAL_COMPLEXITY'] + np.random.uniform(sumessst),
'sumLOC_EXECUTABLE' :row['sumLOC_EXECUTABLE'] + np.random.uniform(sumexst),
'sumHALSTEAD_CONTENT' :row['sumHALSTEAD_CONTENT'] + np.random.uniform(sumconst),
'sumHALSTEAD_DIFFICULTY' :row['sumHALSTEAD_DIFFICULTY'] + np.random.uniform(sumdiffest),
'sumHALSTEAD_EFFORT' :row['sumHALSTEAD_EFFORT'] + np.random.uniform(sumeffst),
'sumHALSTEAD_ERROR_EST' :row['sumHALSTEAD_ERROR_EST'] + np.random.uniform(sumerrost),
'sumHALSTEAD_LENGTH' :row['sumHALSTEAD_LENGTH'] + np.random.uniform(sumlengst),
'sumHALSTEAD_LEVEL' :row['sumHALSTEAD_LEVEL'] + np.random.uniform(sumlevst),
'sumHALSTEAD_PROG_TIME' :row['sumHALSTEAD_PROG_TIME'] + np.random.uniform(sumprogst),
'sumHALSTEAD_VOLUME' :row['sumHALSTEAD_VOLUME'] + np.random.uniform(sumvolust),
'sumNUM_OPERANDS' :row['sumNUM_OPERANDS'] + np.random.uniform(sumoperst),
'sumNUM_OPERATORS' :row['sumNUM_OPERATORS'] + np.random.uniform(sumoperandst),
'sumNUM_UNIQUE_OPERANDS' :row['sumNUM_UNIQUE_OPERANDS'] + np.random.uniform(sumuopst),
'sumNUM_UNIQUE_OPERATORS' :row['sumNUM_UNIQUE_OPERATORS'] + np.random.uniform(sumuoprst),
'sumLOC_TOTAL' :row['sumLOC_TOTAL'] + np.random.uniform(sumtolst),
'DEFECTT' :row['DEFECTT'] + np.random.uniform(deftst),
'DEFECT5' :row['DEFECT5'] + np.random.uniform(defest),
'NUMDEFECTS' :row['NUMDEFECTS'] + np.random.uniform(ndefst)
}
A.append(temp)
print(len(A), "dataset created")
df=pd. DataFrame(A)
df.to_csv("A1.csv")
The output is as follows
726 dataset created
AttributeError Traceback (most recent call
last)
in ()
1 print(len(A), "dataset created")
----> 2 df=pd. DataFrame(A)
3 df.to_csv("A1.csv")
5 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/dtypes/cast.py in
maybe_convert_platform(values)
122 arr = values
123
--> 124 if arr.dtype == object:
125 arr = cast(np.ndarray, arr)
126 arr = lib.maybe_convert_objects(arr)
AttributeError: 'dict' object has no attribute 'dtype'
Any help is appreciated
Thank You!
A=[]
if you use curly braces {} rather than block braces [] then the problem
AttributeError: 'dict' object has no attribute 'dtype'
will be solved.
Use this:
A={}

How can I send a sms in Django?

I encountered a problem when trying to send sms using the SMSC service in Django project.
My Celery task for sending email and sms:
def order_created_retail(order_id):
# Task to send an email when an order is successfully created
order = OrderRetail.objects.get(id=order_id)
subject = 'Order №{}.'.format(order_id)
message_mail = 'Hello, {}! You have successfully placed an order{}. Manager will contact you shortly'.format(order.first_name, order.id)
message_sms = 'Your order №{} is accepted! Wait for operator call'
mail_sent = send_mail(
subject,
message_mail,
'email#email.com',
[order.email]
)
smsc = SMSC()
sms_sent = smsc.send_sms(
[order.phone],
str(message_sms)
)
return mail_sent, sms_sent
Email sends correctly, but for sms I get that error:
Task orders.tasks.order_created_retail[f05458b1-65e8-493b-9069-fbaa55083e7a] raised unexpected: TypeError('quote_from_bytes() expected bytes')
function from SMSC library:
def send_sms(self, phones, message, translit=0, time="", id=0, format=0, sender=False, query=""):
formats = ["flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1", "mms=1", "mail=1", "call=1", "viber=1", "soc=1"]
m = self._smsc_send_cmd("send", "cost=3&phones=" + quote(phones) + "&mes=" + quote(message) + \
"&translit=" + str(translit) + "&id=" + str(id) + ifs(format > 0, "&" + formats[format-1], "") + \
ifs(sender == False, "", "&sender=" + quote(str(sender))) + \
ifs(time, "&time=" + quote(time), "") + ifs(query, "&" + query, ""))
# (id, cnt, cost, balance) или (id, -error)
if SMSC_DEBUG:
if m[1] > "0":
print("Сообщение отправлено успешно. ID: " + m[0] + ", всего SMS: " + m[1] + ", стоимость: " + m[2] + ", баланс: " + m[3])
else:
print("Ошибка №" + m[1][1:] + ifs(m[0] > "0", ", ID: " + m[0], ""))
return m
What am I doing wrong?
Thanks!
to solve this problem, I started investigating the functions that were giving out the error.
It turned out that I was passing an incorrect value. the function was expecting a string. And it took me a long time to figure out why editing didn't help.
It turns out that you have to RESET CELERY every time you make an edit.

Writing to a google candlestick chart from python

I'm trying to write from python to a google candlestick chart, and i'm getting a TypeError that doesn't make sense. The google chart says it takes a date column, and 4 number columns, but when i get an error when trying to output it. It's worth noting that i tried to convert them to strings, and i got nothing.
output.write("""<html><head><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script type="text/javascript">google.charts.load('current', {'packages':['corechart']});google.charts.setOnLoadCallback(drawChart);function drawChart() {var data = new google.visualization.DataTable();data.addColumn('number', 'date');data.addColumn('number','low')};data.addColumn('number','open');data.addColumn('number', 'close');data.addColumn('number', 'high');data.addRows([""")
if backtest:
poloData = self.conn.api_query("returnChartData",{"currencyPair": self.pair, "start": self.startTime, "end": self.endTime,"period": self.period})
for datum in poloData:
newTime += period
mycandle = [newTime, datum['open'], datum['close'], datum['high'], datum['low']]
output.write("['" + datum['date'] + "'," + datum['low'] + "," + datum['open'] + "," + datum['close'] + "," + datum['high'])
output.write("],\n")
if (datum['open'] and datum['close'] and datum['high'] and datum['low']):
self.data.append(
BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'],
datum['weightedAverage']))
output.write("""]);var options = {legend:'none};var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));chart.draw(data, options);}</script></head><body><div id="chart_div" style="width: 100%; height: 100%"></div></body></html>""")
my TypeError:
output.write("['" + datum['date'] + "'," + datum['low'] + "," + datum['open'] + "," + datum['close'] + "," + datum['high'])
TypeError: must be str, not int

Working code but pycharm marks tmF and tmR in list as "local variable referenced before assignment", why is this?

I've only recently started programming so there may be a simple answer to this question but I couldn't find it on here. My code works fine for what I want to do but as I am new to this I want to get into the practice of writing good readable code. I am using PyCharm and I noticed it marked some of the code below as not defined. I understand a little about global vs local variables and I guess it has something to do with this but I can't work out why this part of the code works at all if this is the case.
if len(primerF) < 14:
tmF = (no_A_F + no_T_F) * 2 + (no_C_F + no_G_F) * 4
float_tmF = float(tmF)
print("Forward primer tm: " + str(float_tmF))
elif len(primerR) > 13:
tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
no_C_R)
print("Reverse primer tm: " + str(tmR))
if len(primerR) < 14:
tmR = (no_A_R + no_T_R) * 2 + (no_C_R + no_G_R) * 4
print("Reverse primer tm: " + str(tmR))
elif len(primerR) > 13:
tmR = 64.9 + 41*(no_C_R + no_G_R - 16.4) / (no_A_R + no_T_R + no_G_R +
no_C_R)
print("Reverse primer tm: " + str(tmR))
gc_F = (no_G_F + no_C_F)
gc_content_F = float(gc_F) / forward_length * 100
print("Forward GC content: " + str(gc_content_F) + "%")
gc__R = (no_G_R + no_C_R)
gc_content_R = float(gc__R) / reverse_length * 100
print("Reverse GC content: " + str(gc_content_R) + "%")
This block here is marked as name not defined and if I click on the bubble it says: "This inspection warns about local variables referenced before assignment".
list_tm = [**tmF**, **tmR**]
high_tm = max(list_tm)
low_tm = min(list_tm)
You're setting tmF and tmR in conditional blocks that do not cover all possibilities. For example, if primerF is >= 14, tmF will never be set before the list_tm = [tmF, tmR] statement. This will result in a runtime error, which pycharm is warning you about.
One way to fix this is to set default values of tmF and tmR at the top of your code, or to have full conditional coverage by setting tmF and tmR in else (not just elif) blocks.

Best way to write understandable and Python-friendly code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have this code
def testing1(terms, request):
dat = datetime.now(pytz.timezone(geo_timezone(request)))
__start = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'00:00:00'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
__end = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'23:59:59'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
return __start, __end
testing({"month":12,"day":1, "year":"2015"}, request)
But I have a interrogant, whats is the best way to write this code, readable and friendly for the others programers?
Any suggestion for write code extensive in one line like this?
This suggestion is readable?
def testing2(terms, request):
dat = datetime.now(pytz.timezone(geo_timezone(request)))
__start = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T' + '00:00:00' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__end = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T' + '23:59:59' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
return __start, __end
The only hard part to read is where you build your string so I would use .format(). This way you can see the resulting layout and then all of the corresponding entries.
__start = '{}-{}-{}T00:00:00{}:{}'.format(terms['year'],
terms['month'],
terms['day'],
dat.strftime('%z')[:-2],
dat.strftime('%z')[-2:])
__end = '{}-{}-{}T23:59:59{}:{}'.format(terms['year'],
terms['month'],
terms['day'],
dat.strftime('%z')[:-2],
dat.strftime('%z')[-2:])
Personally, I'd go with that second block and call it a day. If you want, you could try aligning it into groups, or messing with str.format():
__start = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T00:00:00' + \
dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__end = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T23:59:59' + \
dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__start = ('{}-{}-{}'.format(terms['year'], terms['month'], terms['day']) +
'T00:00:00' +
'{}:{}'.format(dat.strftime('%z')[:-2], dat.strftime('%z')[-2:]))
__end = ('{}-{}-{}'.format(terms['year'], terms['month'], + terms['day']) +
'T23:59:59' +
'{}:{}'.format(dat.strftime('%z')[:-2], dat.strftime('%z')[-2:]))
You can try something like :
__start = ''.join([terms['year'], '-',
terms['month'], '-',
terms['day'], 'T',
'00:00:00',
dat.strftime('%z')[:-2], ':',
dat.strftime('%z')[-2:]
])
Parenthesis, brackets and braces will help you to keep your lines of code < 80 characters
(and here the join method of string objects is more efficient than operator +)
As your post is about coding style it's hard to not mention the PEP8 if you don't know it already.

Categories