473,657 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

*Naming Conventions*

Okay,

I hear you saying 'not another naming conventions thread'. I've read
through Google and the 'naming conventions' threads were rather
*spelling conventions* threads.

I'm not interested in camelCase versus camel_case or anything
mentioned in 'PEP 8 -- Style Guide for Python Code'. What I'm looking
for is hints or ideas how to name your variables and especially how to
name functions, methods and classes.

I know this depends on what the function is doing. If I know what it
is doing I should be able to give them a desciptive name. But actually
I'm often not able. Especially when the task is quite similar to
another function or Class.

Recently I wrote this code and noticed that I was completely lost in
giving these objects names to describe and distinguish them:

for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer

The 'tips' I got through some postings or articles on the net are: if
a function simply tests something and returns a boolean call it

def is_<whatever_yo u_are_testing_f or>():
pass

like 'is_even'.

Makes sense. The other thing I captured was to use something like

def get_values():

.... Makes sense, too, but aren't all functions getting something?

So if someone had a similar dilemma to mine and could tell me how he
dealt with that, I'd be grateful...
Thorsten
Jun 3 '07 #1
23 2426
In <MP************ ************@ne ws.individual.d e>, Thorsten Kampe wrote:
Recently I wrote this code and noticed that I was completely lost in
giving these objects names to describe and distinguish them:

for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer
Wow, I know you don't want to talk about "spelling conventions" but here
you are mixing many of them. :-)

I don't know if it makes sense for your code, but maybe you can move the
``if`` condition into the class of `myAnswer` as overloaded ``in``
operator. Then this can be written as:

for valid_answer in valid_answers:
if valid_answer in my_answers:
my_options['style'] = valid_answer
The 'tips' I got through some postings or articles on the net are: if
a function simply tests something and returns a boolean call it

def is_<whatever_yo u_are_testing_f or>():
pass
The other typical boolean test prefix is 'has_'.
like 'is_even'.

Makes sense. The other thing I captured was to use something like

def get_values():

... Makes sense, too, but aren't all functions getting something?
So you may reduce this to just `values()`. On the other hand there is the
convention to name functions and methods as verbs that are "doing"
something.

Ciao,
Marc 'BlackJack' Rintsch
Jun 3 '07 #2
On Jun 4, 5:03 am, Thorsten Kampe <thors...@thors tenkampe.dewrot e:
for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer
First, for small loops with loop variables whose meaning is obvious
from context, the most readable name is usually something like 'i' or
'j'. It avoids unnecessary duplication and clutter. Of course, just as
physically turning your head to look in the rear view mirror is
necessary in a driving test but stupid for real driving, you are
likely to be penalised for this if you do it in an educational setting
or somewhere else where daft coding conventions are strictly enforced
(I once worked in a company that had library constants 'Zero' and
'One' defined because the coding conventions insisted on absolutely no
unnamed 'magic numbers' - spelling the numbers using letters
apparently didn't count).

Second, when naming a member, you should take into account that
references will already be specifying what the whole class describes.
That is, provide new information where possible, and avoid unnecessary
repetition.

Since Python is dynamically typed, it can be useful for names to
describe the datatype of the content at times (though not to the
Hungarian notation extreme that is common is C code, esp. for
Windows). And while most variable names are nouns, sometimes
adjectives are most appropriate - esp where the noun is already clear
from context.

Based on this, your code might become something like...

for i in validanswers:
if myAnswers.curre nt in myAnswers.valid List [i]:
MyOptions['style'] = i

'i'
Its obviously a validanswer since it is one of
the validanswers.

'myAnswers.curr ent'
I know its related to myAnswers, but the
adjective 'current' tells me more about this
specific member.

'myAnswers.vali dList'
'valid' on its own is useful extra information,
but suggests a flag field. validList is better
since it avoids that confusion.

Depending on what myAnswers.myans wer actually holds, it might
alternately be renamed something like myAnswers.uid or myAnswers.id (a
[unique] identifier code identifying the answer) or myAnswers.text
(the text of the answer).

It is also often useful to use a convention where a prefix identifies
whether a name is a (p)arameter, (l)ocal variable, or (m)ember
variable - no prefix for functions, usually. For example, a simple
setter method may logically use the same name for the parameter
specifying the value to write, the member variable to write to, and
(barring a prefix along the lines of 'Set') the method name.

Jun 3 '07 #3
On Jun 3, 4:32 pm, Steve Howell <showel...@yaho o.comwrote:
I also still waste brain cycles on naming
dictionaries. Sometimes I name the dictionary after
the values it stores, sometimes after the keys it
uses, and sometimes after both.
I was in the same boat but now I've pretty much settled to the
convention `key2value`, e.g.:

name2func = {
'sum' : sum,
'avg' : lambda values: sum(values) / float(len(value s))
'product' : lambda values: reduce(operator .mul,values,1),
}

word2positions = {
'dog' : [3, 45, 79, 840],
'cat' : [56, 97, 810],
}

At some point I was torn between this and the plural form, i.e.
`keys2values`, but that's ambiguous in cases where each key or value
is a collection, such as the 'positions' above.

While we're at it, although it's not strictly a naming convention
issue I still waste brain cycles on where to put the import statements
that are used only once or twice in a module. Should
(1) all imports be at the global scope at the top of the module, or
(2) be imported in the function or method they are actually used ?

Reasons for (1)
---------------
- PEP-8 compatible.
- Easy to see all external dependencies in one place.

Reasons for (2)
---------------
- Point of import closer to point of use; easy to notice if a given
import is not used any more after refactoring.
- Less name pollution.
- Faster name lookup in locals (might make a difference for tight
loops).

I usually go for (1), at least until the number of global imports in
the top remains in single digits. After some point though I often
localize the standard library imports that are used only once or twice
(the third-party and local application imports are almost always
global). Any others that are not strictly PEP-8 compliant on this ?

George

Jun 3 '07 #4
On Jun 3, 11:03 pm, Thorsten Kampe <thors...@thors tenkampe.dewrot e:
Okay,

I hear you saying 'not another naming conventions thread'. I've read
through Google and the 'naming conventions' threads were rather
*spelling conventions* threads.

I'm not interested in camelCase versus camel_case or anything
mentioned in 'PEP 8 -- Style Guide for Python Code'. What I'm looking
for is hints or ideas how to name your variables and especially how to
name functions, methods and classes.
In my code:

* The most common form of a function/method name is verb_noun. Other
common patterns are adjective_noun, noun_to_noun or noun2noun (for
conversions), and noun_of_noun.

* Classes nearly always have AdjectiveNoun names.

* Loop indices often have single-letter names (typically i/j/k or x/
y), or names that are the singular form of the list name (e.g., "for
ballot in self._ballots") . For iterating over files, I use "line".

Jun 3 '07 #5
Thorsten Kampe wrote:
for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer
I usually try to avoid using "my" because I find it obscures a better
understanding of what is really going

--
Michael Hoffman
Jun 4 '07 #6
Michael Hoffman wrote:
Thorsten Kampe wrote:
>for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer

I usually try to avoid using "my" because I find it obscures a better
understanding of what is really going
....on.

Whoops, sorry about missing the last word of that message.
--
Michael Hoffman
Jun 4 '07 #7
In <11************ **********@q75g 2000hsh.googleg roups.com>, George Sakkis
wrote:
While we're at it, although it's not strictly a naming convention
issue I still waste brain cycles on where to put the import statements
that are used only once or twice in a module. Should
(1) all imports be at the global scope at the top of the module, or
(2) be imported in the function or method they are actually used ?

[…]

Reasons for (2)
---------------
- Point of import closer to point of use; easy to notice if a given
import is not used any more after refactoring.
`pylint` reports unused imported names. I don't follow PEP8 only if it's
not possible otherwise. But cyclic imports are bad anyway. :-)

And if the import is *really* expensive and only needed in some special
circumstances.

Ciao,
Marc 'BlackJack' Rintsch
Jun 4 '07 #8
On Jun 4, 12:20 am, Ninereeds <stephenhorne.. .@aol.comwrote:
On Jun 4, 5:03 am, Thorsten Kampe <thors...@thors tenkampe.dewrot e:
for validanswer in validanswers:
if myAnswers.myans wer in myAnswers.valid Answers[validanswer]:
MyOptions['style'] = validanswer

First, for small loops with loop variables whose meaning is obvious
from context, the most readable name is usually something like 'i' or
'j'.
'i' and 'j' are the canonical names for for loops indices in languages
that don't support proper iteration over a sequence. Using them for
the iteration variable of a Python for loop (which is really a
'foreach' loop) would be at best confusing.
(snip)
Based on this, your code might become something like...

for i in validanswers:
if myAnswers.curre nt in myAnswers.valid List [i]:
MyOptions['style'] = i
And this is *exactly* what one should not do in Python. If you want a
generic name here, use 'item' instead.
It is also often useful to use a convention where a prefix identifies
whether a name is a (p)arameter, (l)ocal variable, or (m)ember
You don't have to use any kind of prefix for attributes ('member' is
not a Python idiom - remember that in Python, a method is also an
attribute...) since the use of 'self' is mandatoy.

And you usually don't need to distinguish 'local' from 'parameters',
since
1/ parameters names *are* local
2/ pythonic methods and functions tends to be short, so you usually
know which names are params.
FWIW, prefixing names this way is something I've almost never seen in
Python code.
variable - no prefix for functions, usually. For example, a simple
setter method
Python has a pretty good support for computed attributes (look for
'property'), so you don't need explicit getters/setters.
Jun 4 '07 #9
br************* ****@gmail.com wrote:
On Jun 4, 12:20 am, Ninereeds <stephenhorne.. .@aol.comwrote:
>First, for small loops with loop variables whose meaning is obvious
from context, the most readable name is usually something like 'i' or
'j'.

'i' and 'j' are the canonical names for for loops indices in languages
that don't support proper iteration over a sequence. Using them for
the iteration variable of a Python for loop (which is really a
'foreach' loop) would be at best confusing.

While that is true, I guess it is commonplace to use i, j, k and n
(maybe others) in constructs like

for i in range(len(data) ):
do_stuff(data[i])

Or should the good python hacker do that differently? Hope not ;).

/W
Jun 4 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
320
by: Cristof Falk | last post by:
I wanted to get a feel. The documentation gives naming conventions for public/protected members. Is this truly widely adopted? And what about using the same conventions for private members and variables? My coding preference is to use this everywhere (banish Hungarian and follow the capitalization rules) but I need to sell it to team members.
7
2471
by: cmiddlebrook | last post by:
Hi there, I keep finding myself getting inconsistent with naming conventions for things like member variables, class names etc and I just want to find something that suits me and stick to it. I am wondering if there are any naming conventions around that are deemed suitable by the general C++ community. I have googled around and I can't find much - mostly long lists of hungarian-like prefixes which is not really what I'm after.
1
6537
by: clintonG | last post by:
Does the use of DTD, XML Schema and similar constructs adopt the use of C# naming conventions? If so how do I make the distinction of how to apply C# conventions with XML elements, attributes and so on? Any referrals to resources that discuss or document XML Naming Conventions? -- <%= Clinton Gallagher, "Twice the Results -- Half the Cost" Architectural & e-Business Consulting -- Software Development NET...
4
7144
by: Mark Broadbent | last post by:
stupid question time again to most of you experts but this is something that continually bothers me. I am trying to get into the habit of naming variables and controls in an assembly as per convensions. The thing is that Ive never really get the full reference to check against. Ive seen a couple of articles, but there always seems to be a bit missing. I also always seem to run into conflicting convensions both in code samples themselves...
3
4341
by: clintonG | last post by:
Does the use of DTD, XML Schema and similar constructs adopt the use of C# naming conventions? If so how do I make the distinction of how to apply C# conventions with XML elements, attributes and so on? Any referrals to resources that discuss or document XML Naming Conventions? -- <%= Clinton Gallagher, "Twice the Results -- Half the Cost" Architectural & e-Business Consulting -- Software Development NET...
5
6159
by: rastaman | last post by:
Hi all, I know of the existence of Object Naming Conventions for Visual Basic 6. Now I'm reading some books about VB .NET, but the names used for the objects are button1, picturebox1, etc. I wonder if I can use the same naming conventions as for VB6 ? If so, what about the names for the new objects in .NET. Kind regards rastaman
4
5441
by: Patrick | last post by:
what are the general naming conventions for vb.net controls. esp txtUserName, lblPassword, btnSubmit What are the prefixes for the controls???? I've tried to search hi and low on the net, but in vain. I'd much appreciate it if someone could guide me with regards to this. All i need are standards for me to follow by my self. Cuz i'm finding it difficult to make my own darn standards.
9
3806
by: kevininstructor | last post by:
Greetings, I am in the process of creating naming conventions for VB.NET controls i.e. CheckBox -> chkShowThisOnStartup ListBoxt -> lstSomeList What I am looking for other developers input for Window.Form controls and what they are using for naming controls.
35
12175
by: Smithers | last post by:
Is it common practise to begin the name of form classes with "frm" (e.g., frmOneForm, frmAnotherForm). Or is that generally considered an outdated convention? If not "frm" what is a common or recommended practise? Thanks.
1
801
by: Philipp Post | last post by:
Marcello, Not a big surprise as naming conventions have a lot to do with personal prefernces. There are a lot of threads in comp.databases and the other database groups. Just do a search for "naming conventions" in the groups. In my oppinion one of the good conventions is presented by Joe Celko in "SQL Programming Style". I would suggest reading it and pick up
0
8325
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8844
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8742
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8621
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7354
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1971
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1734
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.