How To Name A Module Without Conflict With Variable Name?
Solution 1:
Your code wouldn't actually work, because assigning to the local variable petition
means Python will treat all references to that name as local, so won't find the global reference which is to the module, causing a NameError.
You can import the module with a different name:
import petition as petition_module
Or you can import the things you need directly:
from petition importPetition, check_if_someone_can_sponsor_a_petition
For more clean up you might consider making check_if_someone_can_sponsor_a_petition a classmethod of Petition.
Solution 2:
You don't have to use such qualified names if you don't want to. For example, calling your module petitions
you might write
from petitions importPetition, check_if_someone_can_sponsor_a_petition
This copies the names into your local namespace, so it's then OK to write stuff like
ifcheck_if_someone_can_sponsor_a_petition(a):
petition =Petition(3) # this is no longer so ugly.
Of course if you were instead to call your module petition
it would be a very bad idea to then have a variable of the same name ...
Solution 3:
Class names should be written with the CapsWords convention, variables all lower case, functions lower case with underscores. I think alot of people use a trailing underscore to avoid naming confilcts. It might be ugly but this is the convention as of PEP 8. See the link below for the section on Naming Conventions.
https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions
Hope this helps!
Solution 4:
Not sure if it anwsers your question, but you can import your module with the 'as' directive to define the local name of your choice for the module:
import petition as pet
if pet.check_if_someone_can_sponsor_a_petition(a):
petition = pet.Petition(3)
This may solve your name conflict.
Post a Comment for "How To Name A Module Without Conflict With Variable Name?"